当将实现结构分配给类型为var
的变量时,使用let
和protocol
实现属性的行为不同。
protocol Req {
var path: String? { get }
}
extension Req {
var path: String? { return "Req" }
}
struct LetReq: Req {
let path = "LetReq"
}
struct VarReq: Req {
var path: String? { return "VarReq" }
}
var req: Req!
req = VarReq()
req.path // prints "VarReq"
req = LetReq()
req.path // prints "Req" not "LetReq" which seems very awkward.
这是斯威夫特设计的行为吗?
最佳答案
我认为这是一个编译器错误。如果您将LetReq
设为可选字符串,它将按预期工作:
struct LetReq: Req {
let path: String? = "LetReq"
}
File a bug苹果。