我在 swift 中玩了一些代码,遇到了一个有趣的案例。让我们从一个小序言开始:假设您创建了一些可选变量:
let a: String? = "abcd"; let b: Int? = 4
print(
"Type of \(a) is \(type(of: a))" //Type of Optional("abcd") is Optional<String>
"Type of \(b) is \(type(of: b))", //Type of Optional(4) is Optional<Int>
separator: "\n"
)
然后你强制解开这样的类型au
并且bu
不是可选的。
let au = a!; let bu = b!
print(
"Type of \(au) is \(type(of: au))", //Type of abcd is String
"Type of \(bu) is \(type(of: bu))", //Type of 4 is Int
au + String(bu), //abcd4
separator: "\n"
)
看起来很合理,但是当您尝试将相同的代码应用于Optional<Any>
:
let a: Any? = "abcd"; let b: Any? = 4
let au = a!; let bu = b!
print(
"Type of \(a) is \(type(of: a))", //Type of Optional("abcd") is Optional<Any>
"Type of \(b) is \(type(of: b))", //Type of Optional(4) is Optional<Any>
"Type of \(au) is \(type(of: au))", //Type of abcd is String
"Type of \(bu) is \(type(of: bu))", //Type of 4 is Int
//au + String(bu),
separator: "\n"
)
但是现在如果你尝试做同样的连接au + String(bu)
,swift 会产生编译错误,即使这两个变量已知是某种具体的类型,正如 swift 本身所报告的那样。错误是:
error: protocol type 'Any' cannot conform to 'LosslessStringConvertible' because only concrete types can conform to protocols
这当然看起来像一个错误,不是吗。请分享您的意见。