Swift泛型参数推断错误

时间:2017-10-13 21:11:43

标签: ios swift

我得到了快速编译错误,我无法弄清楚如何修复。请看下面的代码片段。编译器错误在最后一行输出我输入注释行的消息。 Xcode 8.3.3

class View {
}

protocol FieldView {
    associatedtype Value

    var value: Value { get set }
}

class FormView<Field: View>: View where Field: FieldView {
    let fields: [Field]

    init(fields: [Field]) {
        self.fields = fields
    }
}

class BoolFieldView: View, FieldView {
    var value: Bool = false
}

class TextFieldView: View, FieldView {
    var value: String = ""
}

let fields = [BoolFieldView(), TextFieldView()]

// error: generic parameter 'Field' could not be inferred
let form = FormView(fields: fields)

1 个答案:

答案 0 :(得分:-1)

 let fields1 = [BoolFieldView()]
 let fields2 = [TextFieldView()]

 let form1 = FormView(fields:fields1)
 let form2 = FormView(fields:fields2)

上面的代码可以用Xcode 9编译。