Last active
September 17, 2017 15:16
-
-
Save roana0229/0d0a531180742ad8024621449ed19229 to your computer and use it in GitHub Desktop.
関数を引数として渡す書き方のポイントのおまけ調べ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func printFunc(str: String) { | |
print(str) | |
} | |
// Int2つを、引数として宣言 | |
func someFunc(a: Int, b: Int) -> String { | |
return "a: \(a), b: \(b)" | |
} | |
// Int2つを持つタプルを、引数として宣言 | |
func hogeFunc(q: (a: Int, b: Int)) -> String { | |
return "a: \(q.a), b: \(q.b)" | |
} | |
// ラベルなしInt2つを持つタプルを、引数として宣言 | |
func fugaFunc(q: (Int, Int)) -> String { | |
return "a: \(q.0), b: \(q.1)" | |
} | |
let parameters = (x: 0, y: 1) | |
let array: [(Int, Int)] = [parameters] | |
print("--- someFunc ---") | |
// someFunc(parameters) // Swift3から引数2つの関数に対して、1つのタプルを渡せない | |
// error: passing 2 arguments to a callee as a single tuple value has been removed in Swift 3 | |
// https://github.com/apple/swift/blob/master/test/Misc/misc_diagnostics.swift#L140 | |
array.map(someFunc).forEach(printFunc) | |
array.map{ someFunc(a: $0, b: $1) }.forEach(printFunc) // 関数を渡さない場合、このように解釈されている? | |
print("--- hogeFunc ---") | |
// hogeFunc(q: parameters) // ラベルが違うので渡せない | |
// error: cannot convert value of type '(x: Int, y: Int)' to expected argument type '(a: Int, b: Int)' | |
array.map(hogeFunc).forEach(printFunc) | |
array.map{ hogeFunc(q: $0) }.forEach(printFunc) | |
print("--- fugaFunc ---") | |
fugaFunc(q: parameters) // ok | |
array.map(fugaFunc).forEach(printFunc) | |
array.map{ fugaFunc(q: $0) }.forEach(printFunc) |
mapにタプルが渡ってきた時、タプルを展開した状態
or 展開していない状態
のどちらでも解釈できる
array.map{ (a, b) -> String in
someFunc(a: a, b: b)
}.forEach(printFunc)
array.map{ (q: (Int, Int)) -> String in
someFunc(a: q.0, b: q.1)
}.forEach(printFunc)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
someFuncが呼べない理由とは別件だけど、どちらでも同じ結果を出力する。
しかし、このようにすると
$0: (Int, Int)
と解釈されていてコンパイルエラー