我建议使用带有可选的值的元组,然后创建代码相应地打开它们。
类型Any
应该尽量少用,你知道这是无论是String
或Int
意味着元组可能是你使用的情况下,最合适的解决方案的事实。
func someFuction(type: String) -> (String?, Int?) {
//Do stuff here
}
展开可选开关例如:
let sometuple: (string: String?, int: Int?) = ("Hi", 10)
switch sometuple {
case let (.some(s), .some(i)):
print("String: \(s), Int: \(i)")
case let (.some(s), nil):
print(s)
case let (nil, .some(i)):
print(i)
case (nil, nil):
print("Nothing")
}
//prints "String: Hi, Int: 10"
这部作品的原因是因为Optional
是一个枚举:
enum Optional<T> {
case some(x:T)
case none
}
在什么情况下是否有意义这样做呢? – Alexander
使用'任何'如果你必须声明该功能 – duan
* facepalm *当然,谢谢!没想到这个 –