Unikorn
Unikorn

Reputation: 1151

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

example:

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

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

I want to be able to do initialize FanSpeed this way:

let fs:FanSpeed = 4

I know there is a protocol I can conform to to support this, but just can't remember at this moment. Thanks for reading!

Upvotes: 3

Views: 99

Answers (1)

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9935

You are looking for a ExpressibleByIntegerLiteral protocol.

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
    }

}

Now, you can init a variable of type FanSpeed with an integer value.

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]
let fanSpeed: FanSpeed = .init(fanSpeed: 3)

Upvotes: 6

Related Questions