【发布时间】:2019-11-27 13:00:31
【问题描述】:
我在 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
这肯定看起来像一个错误,不是吗。请分享您的意见。
【问题讨论】:
-
请注意,您没有将任何变量从
Any?转换为String或Int,只是将它们解包到Any。调用type(of:)的结果仍然很奇怪,希望有人能解释一下。
标签: swift any forceunwrap swift-optionals