假设我有一个返回a的方法,tuple并且该元组有一个键.如何使用密钥而不是索引或位置访问该元组?
import Cocoa
func getValues() -> (Int, Int) {
return (firstVal: 1, secondVal: 2)
}
let result = getValues()
print(result)
print(result.firstVal)
Run Code Online (Sandbox Code Playgroud)
在上面print(result)返回元组,减去键并print(result.firstVal)抛出错误.
error: Tuples.playground:3:7: error: value of tuple type '(Int, Int)' has no member 'firstVal'
print(result.firstVal)
^ ~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
您还需要在函数签名中包含标签.
func getValues() -> (firstVal: Int,secondVal: Int) {
return (firstVal: 1, secondVal: 2)
}
Run Code Online (Sandbox Code Playgroud)
typealias为自定义元组定义一个更好的方法:
typealias ValueTuple = (firstVal: Int,secondVal: Int)
func getValues() -> ValueTuple {
return (firstVal: 1, secondVal: 2) // or even return (1,2) works
}
Run Code Online (Sandbox Code Playgroud)