Home > front end >  How can I use same logic for a Type in optional/non-optional case
How can I use same logic for a Type in optional/non-optional case

Time:12-26

I have a closure that adds zero to left part of a number in a condition and return String. The number type is Int but it must work if the Type is optional Int.

I ended up to repeat my code, my goal is stop repeating my code in the way that my code works for Int and Int?

extension Int {
    var addLeftZero: String { addLeftZeroClosure(self) }
}


extension Optional where Wrapped == Int {
    var addLeftZero: String {

        if let unwrappedValue: Wrapped = self { return addLeftZeroClosure(unwrappedValue) }
        else { return "00" }
        
    }
}



let addLeftZeroClosure: (Int) -> String = { value in

    if (value >= 10) { return String(describing: value) }
    else { return "0"   String(describing: value) }
    
}

CodePudding user response:

You could do something like this:

extension Int {
    var addLeftZero: String {
        String(format: "d", self)
    }
}

extension Optional where Wrapped == Int {
    var addLeftZero: String {
        self?.addLeftZero ?? "00"
    }
}

Example usage:

let a: Int = 1
let b: Int? = 2
let c: Int? = nil

print(a.addLeftZero) // Prints: 01
print(b.addLeftZero) // Prints: 02
print(c.addLeftZero) // Prints: 00

Although Xcode code-completion will automatically do a?.addLeftZero instead of a.addLeftZero.

  • Related