ぜのぜ

しりとりしようぜのぜのぜのぜ

21日目 今日の日記です

日記

今日はワクチン接種を受けに久々に外の世界に出た.登校中の子供や出勤中の大人がいて世界は動いてるんだなぁってちょっと感動した.

今日書いたコード

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if let min = array.min(),
       let max = array.max() {
        return (min, max) // (1)
    } else {
        return nil
    }
}

minMax(array: Array(0...10))?.min // => 0

let minMax: (min: Int, max: Int)
minMax = (1, 2) // (2)
minMax.min // => 1

// コンパイルエラー
// let minMachs: (min: Int, machs: Int) = minMax

初めて知ったこと

型定義でタプルの要素の名前が決まっていれば関数から値を返すときや代入するときに名前を指定する必要はない.今回読んだところでは(1)のような関数の例について書いてあったが,(2)のようにすることも可能.

Note that the tuple’s members don’t need to be named at the point that the tuple is returned from the function, because their names are already specified as part of the function’s return type. https://docs.swift.org/swift-book/LanguageGuide/Functions.html#:~:text=Note%20that%20the%20tuple%E2%80%99s%20members%20don%E2%80%99t%20need%20to%20be%20named%20at%20the%20point%20that%20the%20tuple%20is%20returned%20from%20the%20function%2C%20because%20their%20names%20are%20already%20specified%20as%20part%20of%20the%20function%E2%80%99s%20return%20type.