Swift 3.0の5、制御フロー

10424 ワード

1.For-inサイクルfor...inループを使用してシーケンスを巡回します.
for index in 1...5 {  // index      ,             ,     let  。
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

シーケンスの各値が不要な場合は、遍歴名の代わりに下線を使用して値を無視します.
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
//    : "3 to the power of 10 is 59049"
for...in配列要素のループ:
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
for...inディクショナリキー値ペアのループ:
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs

2.Whileサイクル
While文whileループの汎用フォーマット:
while condition {
    statements
}
// while       condition  ,   condition   true,            condition   false。

次のようになります.
var index = 0
while index < 3 {
    print "index: \(index)"
    index += 1
}
// index: 0
// index: 1
// index: 2

Repeat-Wehile文
Repeat-Whileループの一般的なフォーマット:
repeat {
    statements
} while condition
// repeat-while     condition           。            false 。

次のようになります.
var index = 0
repeat {
    print "index: \(index)"
    index += 1
}while index < 3
// index: 0
// index: 1
// index: 2

3.条件文
If文
最も簡単な形式:
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
}
//    : "It's very cold. Consider wearing a scarf."
else文付きif文:
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
//    : "It's not that cold. Wear a t-shirt."

複数のブランチを持つif文:
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else { //   else       
    print("It's not that cold. Wear a t-shirt.")
}
//    : "It's really warm. Don't forget to wear sunscreen."

Switch文
一般的な一般的なフォーマット:
switch some value to consider {
case value 1:
    respond to value 1
case value 2,
value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}

注意:caseに対応する文は空にできません.あるcaseに一致し、そのcaseに対応する文を実行すると、すぐにswitch文から飛び出します.
文字または文字列が一致し、栗を挙げる:
let someCharacter: Character = "z"
switch someCharacter {
case "a":
    print("The first letter of the alphabet")
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}
//    : "The last letter of the alphabet"

区間マッチング、栗を挙げる:
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
//    : "There are dozens of moons orbiting Saturn."

元組マッチング、栗を挙げる:
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("(0, 0) is at the origin")
case (_, 0):             //               
    print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):             //               
    print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):   //       
    print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
//    : "(1, 1) is inside the box"

マッチタイムバインド、栗を挙げる:
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):  //            x
    print("on the x-axis with an x value of \(x)")
case (0, let y):  //            y
    print("on the y-axis with a y value of \(y)")
case let (x, y):  //            x   y
    print("somewhere else at (\(x), \(y))")
}
//    : "on the x-axis with an x value of 2"
whereセクションを使用して、追加の状況を確認します.
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:  // x == y    
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y: // x == -y    
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):                     
    print("(\(x), \(y)) is just some arbitrary point")
}
//    : "(1, -1) is on the line x == -y"

マルチケースの場合:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
     "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) is not a vowel or a consonant")
}
//   : "e is a vowel"

4.制御遷移文
Swiftには、5つの制御遷移文があります.
  • continue
  • break
  • fallthrough
  • return
  • throw

  • Continue文continue文は、ループが次に行うことを停止し、次のループを開始することを示します.例を挙げます.
    let puzzleInput = "great minds think alike"
    var puzzleOutput = ""
    for character in puzzleInput.characters {
        switch character {
        case "a", "e", "i", "o", "u", " ": //        ,         
            continue
        default:
            puzzleOutput.append(character)
        }
    }
    print(puzzleOutput)
    //    : "grtmndsthnklk"
    

    Break文Break直ちに全体Switchまたは循環コードブロックから飛び出します.
    let numberSymbol: Character = " "  // Simplified Chinese for the number 3
    var possibleIntegerValue: Int?
    switch numberSymbol {
    case "1", "١", " ", "๑":
        possibleIntegerValue = 1
    case "2", "٢", " ", "๒":
        possibleIntegerValue = 2
    case "3", "٣", " ", "๓":
        possibleIntegerValue = 3
    case "4", "٤", " ", "๔":
        possibleIntegerValue = 4
    default:
        break  //      ,    Swich  
    }
    if let integerValue = possibleIntegerValue {
        print("The integer value of \(numberSymbol) is \(integerValue).")
    } else {
        print("An integer value could not be found for \(numberSymbol).")
    }
    //    : "The integer value of   is 3."
    

    Fallthrough文Switch文は、デフォルトでcaseに一致すると飛び出し、その後のcaseに一致しません.ただし、動作を貫通する必要がある場合は、各caseの末尾にfallthroughキーワードを使用できます.
    let integerToDescribe = 5
    var description = "The number \(integerToDescribe) is"
    switch integerToDescribe {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        description += " a prime number, and also"
        fallthrough  // fallthrough ,       default    。
    default:
        description += " an integer."
    }
    print(description)
    //    : "The number 5 is a prime number, and also an integer."
    

    文にラベルを付ける
    ループと条件文は互いに埋め込むことができるため、明示的にbreakまたはcoontinue具体的にどのループまたは条件文が必要かを明記することができるので、この文にラベルを付けることができ、一般的なフォーマットは:
        :    Switch   {
        statements
    }
    

    栗を挙げます.
    let finalSquare = 25
    var square = 0
    var diceRoll = 0
    
    gameLoop: while square != finalSquare {  //   ,        gameLoop  
        diceRoll += 1
        if diceRoll == 7 { diceRoll = 1 }
        switch square + diceRoll {
        case finalSquare:
            break gameLoop     //     gameLoop,    Switch       
        case let newSquare where newSquare > finalSquare:
            continue gameLoop  //    gameLoop,    
        default:
            square += diceRoll
            square += board[square]
        }
    }
    print("Game over!")
    

    guard...else文guard文は、guard文の後のコードを実行するために真の条件を必要とします.そうしないと、elseの文のみが実行されます.
    注意:1.else分岐は、return,break,continue,throwまたはfatalError()のような戻り値のない関数で終わる.2.guard条件では、オプションバインドによって付与された変数または定数がguardコードブロック全体の終了後に使用可能である.
    func greet(person: [String: String]) {
        guard let name = person["name"] else {
            return
        }
        
        print("Hello \(name)!")  // name    guard            
        
        guard let location = person["location"] else {
            print("I hope the weather is nice near you.")
            return
        }
        
        print("I hope the weather is nice in \(location).")
    }
    
    greet(["name": "John"])
    //    : "Hello John!"
    //    : "I hope the weather is nice near you."
    greet(["name": "Jane", "location": "Cupertino"])
    //    : "Hello Jane!"
    //    : "I hope the weather is nice in Cupertino."
    

    #available文
    APIの可用性を確認するには、次のようにします.
    if #available(iOS 10, macOS 10.12, *) {
        // iOS    iOS 10 API, macOS    macOS 10.12 API。
    } else {
        //        API
    }