转换结构失败,并且:...无法转换为(Casting struct fails with: … is not convertible to)
我有一个协议:
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?
I have a protocol:
protocol Occurrence { var isEmpty: Bool { get } mutating func addOccurrence(occ: Occurrence) -> Occurrence mutating func removeOccurrence(occ: Occurrence) -> Occurrence }And a struct that conforms to that protocol:
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 } } }In the addOccurrence method there is an error as I put it to the comment. What am I missing here? Why can't I cast that instance to NonEmptyOccurrence?
最满意答案
尝试以下方法:
mutating func addOccurrence(other: Occurrence) -> Occurrence { if !other.isEmpty, let otherAsNEO = (other as? NonEmptyOccurrence) { _occurrence = _occurrence + otherAsNEO._occurrence } return self }It turned out that you can cast structs in Xcode 6 beta3, but you cannot in the current stable version (Xcobe 6.2).
更多推荐
发布评论