转换结构失败:...不可转换为
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?
试试这样的东西:
mutating func addOccurrence(other: Occurrence) -> Occurrence {
if !other.isEmpty, let otherAsNEO = (other as? NonEmptyOccurrence) {
_occurrence = _occurrence + otherAsNEO._occurrence
}
return self
}
事实证明,您可以在 Xcode 6 beta3 中转换结构,但在当前的稳定版本 (Xcobe 6.2) 中不能。
我有协议:
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?
试试这样的东西:
mutating func addOccurrence(other: Occurrence) -> Occurrence {
if !other.isEmpty, let otherAsNEO = (other as? NonEmptyOccurrence) {
_occurrence = _occurrence + otherAsNEO._occurrence
}
return self
}
事实证明,您可以在 Xcode 6 beta3 中转换结构,但在当前的稳定版本 (Xcobe 6.2) 中不能。