当类型是关联类型时,无法将类型的值转换为预期的参数类型

时间:2018-02-07 08:20:28

标签: swift

以下是 swift 4 代码:

protocol BarProtocol {
    associatedtype Bar
    var bar:Bar? {get set}
}

class FooClass : BarProtocol {
    //typealias Bar = (String) -> ()
    typealias Bar = (String)
    var bar: Bar?
}

func configFooClass<T:BarProtocol>(fooClass:inout T, bar:T.Bar) {
    fooClass.bar = bar
}
func setupFooClass(fooClass:inout FooClass, bar:FooClass.Bar) {
    configFooClass(fooClass: &fooClass, bar: bar)
}

var fooClass = FooClass()
var barString = "barString"
//let barAction:(String) -> () = { text in
//    print(text)
//}

setupFooClass(fooClass:&fooClass, bar:barString)
print(fooClass.bar) // print: Optional("barString")

到目前为止,它将在控制台中打印“Optional(”barString“)”。现在,String类型中的类FooClass中的associatedtype,因此它可以存储字符串值“barString”。

但如果我将此代码更改为:

protocol BarProtocol {
    associatedtype Bar
    var bar:Bar? {get set}
}

class FooClass : BarProtocol {
    typealias Bar = (String) -> ()
//    typealias Bar = (String)
    var bar: Bar?
}

func configFooClass<T:BarProtocol>(fooClass:inout T, bar:T.Bar) {
    fooClass.bar = bar
}
func setupFooClass(fooClass:inout FooClass, bar:FooClass.Bar) {
    configFooClass(fooClass: &fooClass, bar: bar) 
// Error here: Cannot convert value of type '(String) -> ()' to expected argument type '_.Bar'
}

var fooClass = FooClass()
var barString = "barString"
let barAction:(String) -> () = { text in
    print(text)
}

//setupFooClass(fooClass:&fooClass, bar:barString)
//print(fooClass.bar)
setupFooClass(fooClass:&fooClass, bar:barAction)
fooClass.bar!("lalalalala")

实际上,我只是将FooClass的associatedtype从String更改为(String) - &gt; (),它会有一个arror:无法转换类型'(String) - &gt;的值()'到期望的参数类型'_.Bar'

我不明白,似乎封闭可以作为函数的参数传递。但为什么'String'类型运行良好,但'(String) - &gt; ()'没有?

1 个答案:

答案 0 :(得分:0)

似乎添加@escaping可以解决这个问题......

func setupFooClass(fooClass:inout FooClass, bar:@escaping FooClass.Bar) {
    configFooClass(fooClass: &fooClass, bar: bar)

}