如何在 swift struct/class 类型中支持这种初始化?

How do I support this kind of init in swift struct/class type?

示例:

struct FanSpeed {
    var fanSpeed: Int {
        willSet{
            previousFanSpeed = fanSpeed
        }
    }
    var previousFanSpeed: Int

    init(fanSpeed: Int) {
        self.fanSpeed = fanSpeed
        self.previousFanSpeed = fanSpeed
    }
}

我希望能够以这种方式初始化 FanSpeed:

let fs:FanSpeed = 4

我知道有一个我可以遵守的协议来支持这个,但现在不记得了。感谢阅读!

您正在寻找 ExpressibleByIntegerLiteral 协议。

struct FanSpeed: ExpressibleByIntegerLiteral {
    
    typealias IntegerLiteralType = Int
    
    init(integerLiteral value: Int) {
        self.init(fanSpeed: value)
    }
    
    var fanSpeed: Int {
        willSet{
            previousFanSpeed = fanSpeed
        }
    }
    var previousFanSpeed: Int

    init(fanSpeed: Int) {
        self.fanSpeed = fanSpeed
        self.previousFanSpeed = fanSpeed
    }

}

现在,您可以使用整数值初始化 FanSpeed 类型的变量。

let fanSpeed = FanSpeed(fanSpeed: 3)
let fanSpeed: FanSpeed = 3
let fanSpeed = 3 as FanSpeed
let fanSpeed: [FanSpeed] = [1, 2, 5]
let fanSpeed = [1, 2, 5] as [FanSpeed]