快速型別推斷不適用于函式回傳型別嗎?
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())
我正在操場上嘗試這個。為什么上面一行有錯誤?編譯器不應該Bike從let v: Bike宣告中推斷出型別嗎?
uj5u.com熱心網友回復:
問題是getVehicle回傳一個可選的,你必須宣告
let v: Bike? = VehicleFactory.getVehicle()
此外,您必須在行v中展開print
uj5u.com熱心網友回復:
不能直接回答你的問題。Vadian 已經回答了您的實施,但有一些注意事項:
(_ vehicleType: T.Type = T.self)是沒有意義的。你可以省略它。
其次,我將簡單地將 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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412129.html
標籤:
上一篇:java泛型的類層次結構問題
下一篇:將泛型結構視為特征物件
