我在创建一个方便的 init 方法时遇到问题,该方法然后在具有泛型类型参数的类上调用指定的 init。这是 swift 3.1 XCode 版本 8.3.2 (8E2002) 操场

protocol A {
    var items: [String] { get set }
    func doSomething()
}

struct Section : A {
    var items: [String] = []

    func doSomething() {
        print("doSomething")
        items.forEach { print($0) }
    }
}

class DataSource<T: A> {
    var sections: [T]

    init(sections: [T]) {
        self.sections = sections
    }

    func process() {
        sections.forEach { $0.doSomething() }
    }

    convenience init() {
        var section = Section()
        section.items.append("Goodbye")
        section.items.append("Swift")

        self.init(sections: [section])
    }
}

/*: Client */
var section = Section()
section.items.append("Hello")
section.items.append("Swift")

let ds = DataSource(sections: [section])
ds.process()

如果不存在方便的 init,则/*: Client */部分下的代码将毫无问题地编译和执行。如果我添加了便利 init,我会收到以下编译错误:
cannot convert value of type '[Section]' to expected argument type '[_]'
        self.init(sections: [section])

我不认为这会是一个问题,因为在方便的初始化中,我正在创建一个 Section 结构,它实现了满足 DataSource 类的通用约束的协议(protocol) A。便利 init 正在执行与客户端代码相同的操作,但它无法将 [Section] 转换为 [A]。这是初始化排序问题吗?

最佳答案

泛型占位符满足给定泛型类型的使用——因此在你的 convenience init 中,你不能假设 T 是一个 Section 。它是符合 A 的任意具体类型。

例如,调用者定义一个

struct SomeOtherSection : A {...}

然后使用 T 调用您的便利初始化程序 SomeOtherSection

这种情况下的解决方案很简单,您只需在 DataSource 的扩展中添加便利初始化程序,其中 T 被限制为 Section - 因此允许您使用 init(sections:) 调用 [Section] :
extension DataSource where T == Section {

    convenience init() {
        var section = Section()
        section.items.append("Goodbye")
        section.items.append("Swift")

        self.init(sections: [section])
    }
}

// ...

// compiler will infer that T == Section here.
let ds = DataSource()

关于快速方便的初始化和泛型类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44066573/

10-11 22:15
查看更多