由方法上下文定义的Swift泛型类型

时间:2017-01-03 23:34:28

标签: swift generics

模式的名称是否由结果类型的上下文推断出类型?

例如,在此示例中,我可以使用哪种语言来记录foo方法,并解释需要为方法定义类型?

protocol FooType {
   init()
}

func foo<T: FooType>() -> T {
    return T()
}

struct Bar: FooType {
    init() {
        print("bar")
    }
}


let bar: Bar = foo()
// works returns instance of Bar

let fooType = foo()
// fails because foo doesn't know what type to use

1 个答案:

答案 0 :(得分:2)

You don't need to document this!

Everyone that writes code in Swift knows that to call a generic function, all its type parameters must be inferred and cannot be spoon-fed like this:

foo<Bar>()

People will see foo and say, "Oh I need the compiler to infer the type for this generic parameter." They will understand what this means.