[Swift]#5制御フロー、#6関数


5.制御フロー


for, while, if, guard, switch, break, continue
他の言語とほぼ同じと言ってもいいです.

1.サイクル形成


配列、数値範囲、文字列、ディクシャナリー、...for inループを使用して各要素にアクセスできます.
前の内容で大まかに紹介したことがありますが、よく知っているので、とても忘れやすいです.
for (index, value) in enumarated(arr) {
}

for i in stride(from: 0, to: 10, by: 2) { 
    // 10 은 포함 안됨.
}

for i in stride(from: 0, through: 10, by: 2) { 
    // 10 포함.
}
つけて行こうPythonでは列挙(arr)/range(0,10,2)が混同されることが多い

2. while / repeat ~ while


他の言語のwhile、do~whileと同じです.条件がtrueの場合、条件を考慮せずに繰り返し/最初の実行後に繰り返します.

条件文


1. if ~ else if ~ else


2. switch


SWIFT Switch特性
  • swiftはブレークポイントを書かなくてもいいです.
    別の言語では、各ケースにbreakを掛けないと、swiftではなく次の言語に実行されます.逆に、元のように次のように動作させたい場合は、fallroughを明確に書くことができます.
  • スイッチドアには、tuple、enumなどの整数または文字を入れることができます.
  • switch int(score / 10) {
    case 10, 9: print("A") // , 로 나누기도 가능.
    case 8: print("B")
    case 7: print("C")
    case 6: print("D")
    default: print("F")
    }
    
    // 숫자 범위로 쓰는 것도 가능하다.
    switch score {
    case 90...100: print("A")
    case 80..<90: print("B")
    case 70..<80: print("C")
    case 60..<70: print("D")
    default: print("F")
    }

    3. switch - tuple / where ⭐️


    caseを無視するには、それを入れるだけです.
    let somePoint = (1, 1)
    switch somePoint {
    case (0, 0):
        print("\(somePoint) is at the origin")
    case (_, 0):
        print("\(somePoint) is on the x-axis")
    case (0, _):
        print("\(somePoint) \(y) is on the y-axis")
    case (-2...2, -2...2):
        print("\(somePoint) is inside the box")
    default:
        print("\(somePoint) is outside of the box")
    }
    // Prints "(1, 1) is inside the box"
    値をバインドして使用するか、whereセクションを使用してバインド値の条件を計算できます.
    let anotherPoint = (2, 0)
    switch anotherPoint {
    case (let x, 0):
        print("on the x-axis with an x value of \(x)")
    case (0, let y):
        print("on the y-axis with a y value of \(y)")
    case let (x, y) where x == y:
        print("(\(x), \(y)) is on the line x == y")
    case let (x, y) where x == -y:
        print("(\(x), \(y)) is on the line x == -y")
    case let (x, y):
        print("(\(x), \(y)) is just some arbitrary point")
    }
    // Prints "on the x-axis with an x value of 2"

    4.構文変更の制御


    continue、break、fallrough、return(関数)、throw(エラーハンドル)

    1. continue


    現在の繰り返しのステップをスキップして、次の繰り返しを開始します.

    2. break


    今の繰り返し文から抜け出す.
    or switch文はbreakの前の条件を無視します.default: break

    3. fallthrough


    スイッチドアをCのように動かして、次のステップに進みます.
    +)ラベルを使用して特定の重複文から離れることができますが、あまり使用されません.
    gameLoop: while square != finalSquare {
        diceRoll += 1
        if diceRoll == 7 { diceRoll = 1 }
        switch square + diceRoll {
        case finalSquare:
            // diceRoll will move us to the final square, so the game is over
            break gameLoop
        case let newSquare where newSquare > finalSquare:
            // diceRoll will move us beyond the final square, so roll again
            continue gameLoop
        default:
            // this is a valid move, so find out its effect
            square += diceRoll
            square += board[square]
        }
    }
    print("Game over!")

    5. Early Exit (guard) ⭐️⭐️


    関数またはモジュールで、条件を満たす必要がある変数がある場合は、変数を割り当てた文をチェックします.条件が偽の場合は、文は実行されません.
    func greet(person: [String: String]) {
        // 딕셔너리에 name 이 없으면 그냥 끝남.
        guard let name = person["name"] else { return }
    
        print("Hello \(name)!")
    
        // 딕셔너리에 위치 정보가 없으면 이름, 안내문구만 뽑고 끝남.
        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).")
    }
    // OS 버젼에서 가능한 API 인지 체크해서 사용하는데 사용한다.
    // guard 문으로도 사용 가능
    if #available(iOS 10, macOS 10.12, *) {
        // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
    } else {
        // Fall back to earlier iOS and macOS APIs
    }

    6.関数


    特定のタスクを実行するコードブロック.
    通常、同じ機能を持つ2回以上の繰り返しを関数に組み合わせる.
    関数の名前、パラメータ、戻りタイプ、戻り値の形式は他の言語の関数と同じであるため、swift関数の特殊な点のみをまとめます.

    1.人名にラベルを付ける

    func greet(person name: String) -> String {
        return "Hello, " + name + "!";
    }
    関数を呼び出すときにパラメータを渡すときに使用する名前は、関数内でパラメータを使用する名前とは異なります.
    関数の外部でパラメータ名ラベルを省略する場合に使用します.

    2. tuple? 返却できます。


    実際、これは他の言語でも可能ですが、tupleにラベルを貼ることができるのは特別です.
    そして、tupleへの約束を返すことができるのは特別です.
    func minMax(array: [Int]) -> (min: Int, max: Int) {
        var currentMin = array[0]
        var currentMax = array[0]
        for value in array[1..<array.count] {
            if value < currentMin {
                currentMin = value
            } else if value > currentMax {
                currentMax = value
            }
        }
        return (currentMin, currentMax)
    }
    
    let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
    print("min is \(bounds.min) and max is \(bounds.max)") 
    // 반환하는 튜플의 값을 라벨 이름으로 사용.
    // Prints "min is -6 and max is 109"

    3.関数本体が1行の場合、暗黙的に返されます。


    4.デフォルト値を指定できます。

    func addTwo(first: Int, second: Int = 2) {
        return first + second
    }
    
    addTwo(first: 1) // 3
    addTwo(first: 10, second: 3) // 13

    5.可変パラメータ


    同じタイプのパラメータが複数ある場合、
    パラメータタイプはType...指定した場合、このタイプの0つ以上のパラメータが入力される可能性があります.
    func arithmeticMean(_ numbers: Double...) -> Double {
        var total: Double = 0
        for number in numbers {
            total += number
        }
        return total / Double(numbers.count)
    }
    arithmeticMean(1, 2, 3, 4, 5)
    // returns 3.0, which is the arithmetic mean of these five numbers
    arithmeticMean(3, 8.25, 18.75)
    // returns 10.0, which is the arithmetic mean of these three numbers

    6.INOUTパラメータ


    C上のポインタを使用してアドレス値を渡すように、レプリケーション値は関数で変更されます.
    inoutキーワードを追加することで、関数外の値を変更できます.
    func swapTwoInts(_ a: inout Int, _ b: inout Int) {
        let temporaryA = a
        a = b
        b = temporaryA
    }

    7.関数タイプ


    関数はtypeとして使用できます.
    func addTwoInts(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
    
    // 변수에 함수를 할당 가능.
    var mathFunction: (Int, Int) -> Int = addTwoInts
    パラメータ伝達関数を使用できます.
    func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
        print("Result: \(mathFunction(a, b))")
    }
    printMathResult(addTwoInts, 3, 5)
    // Prints "Result: 8"
    関数を返すこともできます.
    func stepForward(_ input: Int) -> Int {
        return input + 1
    }
    func stepBackward(_ input: Int) -> Int {
        return input - 1
    }
    
    func chooseStepFunction(backward: Bool) -> (Int) -> Int {
        return backward ? stepBackward : stepForward
    }

    8.オーバーラップ関数


    関数で関数を定義できます.では、その関数を使える範囲は大きな関数内です!
    func chooseStepFunction(backward: Bool) -> (Int) -> Int {
        func stepForward(input: Int) -> Int { return input + 1 }
        func stepBackward(input: Int) -> Int { return input - 1 }
        return backward ? stepBackward : stepForward
    }