我有一个协议:
protocol Occurrence {
var isEmpty: Bool { get }
mutating func addOccurrence(occ: Occurrence) -> Occurrence
mutating func removeOccurrence(occ: Occurrence) -> Occurrence
}
符合该协议的结构:
struct NonEmptyOccurrence: Occurrence, Printable {
...
private var _occurrence: Int
var isEmpty: Bool {
get {
return false
}
}
...
mutating func addOccurrence(other: Occurrence) -> Occurrence {
if other.isEmpty {
return self
} else {
//error here: Occurrence is not convertible to NonEmptyOccurrence
_occurrence = _occurrence + (other as NonEmptyOccurrence)._occurrence
return self
}
}
}
在addOccurrence
方法中,我将其添加到评论中时出现错误。我在这里错过了什么?为什么我不能将该实例转换为NonEmptyOccurrence?
答案 0 :(得分:0)
尝试类似:
mutating func addOccurrence(other: Occurrence) -> Occurrence {
if !other.isEmpty, let otherAsNEO = (other as? NonEmptyOccurrence) {
_occurrence = _occurrence + otherAsNEO._occurrence
}
return self
}
答案 1 :(得分:0)
事实证明你可以在Xcode 6 beta3中投射结构,但是你不能使用当前的稳定版本(Xcobe 6.2)。