swift 类型推断是否不适用于函数 return 类型?

Does swift type inference not work with function return types?

swift 类型推断是否不适用于函数 return 类型?

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())

我正在操场上尝试这个。为什么上面一行有错误? 编译器不应该从 let v: Bike 声明中推断类型为 Bike 吗?

问题是getVehicle returns一个可选的,你必须声明

let v: Bike? = VehicleFactory.getVehicle()

此外,您必须在 print

中展开 v

不是您问题的直接答案。 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"