[英]Does swift type inference not work with function return types?
Does swift type inference not work with function return types? swift 类型推断是否不适用于 function 返回类型?
protocol Vehicle {
func numberOfWheels() -> Int
}
struct Car: Vehicle {
func numberOfWheels() -> Int {
return 4
}
}
struct Bike: Vehicle {
func numberOfWheels() -> Int {
return 2
}
}
struct Truck: Vehicle {
func numberOfWheels() -> Int {
return 8
}
}
struct VehicleFactory {
static func getVehicle<T: Vehicle>(_ vehicleType: T.Type = T.self) -> T? {
let id = identifier(for: T.self)
switch id {
case "Car":
return Car() as? T
case "Bike":
return Bike() as? T
default:
return nil
}
}
private static func identifier(for type: Any.Type) -> String {
String(describing: type)
}
}
let v: Bike = VehicleFactory.getVehicle() // ERROR HERE: Cannot convert value of type 'T?' to specified type 'Bike'
print(v.numberOfWheels())
I am trying this in playground.我正在操场上尝试这个。 Why is there an error in above line?
为什么上面一行有错误? Shouldnt the compiler infer the type to be
Bike
from the let v: Bike
declaration?编译器不应该从
let v: Bike
声明中推断出类型为Bike
吗?
The problem is that getVehicle
returns an optional, you have to declare问题是
getVehicle
返回一个可选的,你必须声明
let v: Bike? = VehicleFactory.getVehicle()
Further you have to unwrap v
in the print
line此外,您必须在
print
行中解开v
Not a direct answer to your question.不能直接回答你的问题。 Vadian has already answered but a few notes on your implementation:
Vadian 已经回答了您的实施,但有一些注意事项:
(_ vehicleType: T.Type = T.self)
is pointless. (_ vehicleType: T.Type = T.self)
毫无意义。 You can just omit it.你可以省略它。
Second I would simply add init() to your protocol requirements, get rid of the identifier method, change number of wheels to a computed property:其次,我会简单地将 init() 添加到您的协议要求中,摆脱标识符方法,将轮数更改为计算属性:
protocol Vehicle {
init()
var numberOfWheels: Int { get }
}
struct Car: Vehicle {
let numberOfWheels = 4
}
struct Bike: Vehicle {
let numberOfWheels = 2
}
struct Truck: Vehicle {
let numberOfWheels = 8
}
struct VehicleFactory {
static func getVehicle<T: Vehicle>() -> T { .init() }
}
let v: Bike = VehicleFactory.getVehicle()
print(v.numberOfWheels) // "2\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.