在这种情况下,将Int 分配给typealias 等于没有分配,因为它会被您的符合类型覆盖:
// this declaration is equal since you HAVE TO provide the type for SomeType
protocol SomeProtocol {
typealias SomeType
func someFunc(someVar: SomeType)
}
这样的赋值为SomeType 提供了一个默认类型,它会被SomeClass 中的实现覆盖,但它对于协议扩展特别有用:
protocol Returnable {
typealias T = Int // T is by default of type Int
func returnValue(value: T) -> T
}
extension Returnable {
func returnValue(value: T) -> T {
return value
}
}
struct AStruct: Returnable {}
AStruct().returnValue(3) // default signature: Int -> Int
只有遵守协议,不指定T的类型,才能免费获得该功能。如果您想设置自己的类型,请在结构体中写入typealias T = String // or any other type。
关于提供的代码示例的一些附加说明
您解决了问题,因为您明确说明了参数的类型。 Swift 还会推断您使用的类型:
class SomeClass: SomeProtocol {
func someFunc(someVar: Double) {
print(someVar)
}
}
所以协议的SomeType被推断为Double。
另一个例子,你可以看到类声明中的SomeType 没有引用协议:
class SomeClass: SomeProtocol {
typealias Some = Int
func someFunc(someVar: Some) {
print(someVar)
}
}
// check the type of SomeType of the protocol
// dynamicType returns the current type and SomeType is a property of it
SomeClass().dynamicType.SomeType.self // Int.Type
// SomeType gets inferred form the function signature
但是,如果你这样做:
protocol SomeProtocol {
typealias SomeType: SomeProtocol
func someFunc(someVar: SomeType)
}
SomeType 必须是 SomeProtocol 类型,它可以用于更明确的抽象和更多的静态代码,而这个:
protocol SomeProtocol {
func someFunc(someVar: SomeProtocol)
}
将被动态调度。