转换结构失败,并且:...无法转换为(Casting struct fails with: … is not convertible to)

编程入门 行业动态 更新时间:2024-10-27 18:30:00
转换结构失败,并且:...无法转换为(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).

更多推荐

本文发布于:2023-04-29 10:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   结构   Casting   convertible   fails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!