Skip to content

Instantly share code, notes, and snippets.

@roana0229
Last active September 17, 2017 15:16
Show Gist options
  • Save roana0229/0d0a531180742ad8024621449ed19229 to your computer and use it in GitHub Desktop.
Save roana0229/0d0a531180742ad8024621449ed19229 to your computer and use it in GitHub Desktop.
関数を引数として渡す書き方のポイントのおまけ調べ
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)
@roana0229
Copy link
Author

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