使用泛型类时 Swift 抛出运行时错误

标签 swift generics design-patterns

似乎 swift 在处理泛型类时存在一些问题。似乎这些代码可以编译,但在遇到 println(act.actId) 时会出现运行时错误。它抛出了一个EXC_BAD_ACCESS错误。

对于这个问题还有其他方法或解决方法吗?

public class Item {
    public var id: String
    public init(str: String) {
        id = str
    }
}

public class Account: Item {
    public var actId: String
    public override init(str: String) {
        actId = "antId: \(str)"
        super.init(str: str)
    }
}

public class Keyword: Item {
    public var keywordId: String
    public override init(str: String) {
        keywordId = "keywordId: \(str)"
        super.init(str: str)
    }

}

public class Creator<T: Item> {
    public func parse(str: String) -> T {
        var result: T = T(str: str)
        return result
    }
}

var a = Creator<Account>()
var act = a.parse("Apple")
println(act.actId)

最佳答案

就我而言,这不会在 Playground 上编译。

Subclasses do not inherit their superclass initializers by default -> Apple

您需要将 init() 标记为 required

我已经改变了它,现在它可以工作了

public class Item {
    public var id: String
    public required init(str: String) {
        id = str
    }
}

public class Account: Item {
    public var actId: String
    public required init(str: String) {
        actId = "antId: \(str)"
        super.init(str: str)
    }
}

public class Keyword: Item {
    public var keywordId: String
    public required init(str: String) {
        keywordId = "keywordId: \(str)"
        super.init(str: str)
    }

}

public class Creator<T: Item> {
    public func parse(str: String) -> T {
        let result: T = T(str: str)
        return result
    }
}

var a = Creator<Account>()
var act = a.parse("Apple")
print(act.actId)

参见similar question了解更多详情

关于使用泛型类时 Swift 抛出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32087299/

相关文章:

c# - .NET泛型中重载运算符约束的解决方案

ios - 是否可以为模板函数参数提供默认值?

java - 状态和享元模式

ios - 解析带有指针的对象的服务器查询

ios - 3D Touch、peek 和 pop 崩溃并出现 fatal error : unexpectedly found nil while unwrapping an Optional value

java - 获取泛型类型或泛型实例的类

c# - 在 C# 中控制对内部集合的访问 - 需要模式

language-agnostic - 在其他语言中使用时的 bean 模式名称是什么

ios - 重新加载数据后,我可以在 tableView 中保持相同的位置吗?

ios - 用于 swift 的 sqlite 不稳定