Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending swift optional for default values

Tags:

swift

I'm trying to extend Swift's Optional type with default values. Providing empty values in API requests should raise an exception. I've done this for the String type, but I can't achieve the same result with the Integer type:

extension Optional where Wrapped == String {

    var unwrappedValue: String {

        get {
            switch self {

            case .some(let value):
                return value

            case .none:
                return ""
            }
        }
    }
}

The Integer version is throwing the following Error:

Protocol 'Integer' can only be used as a generic constraint because it has Self or associated type requirements

extension Optional where Wrapped == Integer {

    var unwrappedValue: Integer {

        get {
            switch self {

            case .some(let value):
                return value

            case .none:
                return 0
            }
        }
    }
}
like image 631
filip.karas Avatar asked Feb 18 '26 23:02

filip.karas


1 Answers

If you use this for a lot of Types you might want to consider the following addition to the answer of Leo Dabus:

protocol Defaultable {
    static var defaultValue: Self { get }
}

extension Optional where Wrapped: Defaultable {
    var unwrappedValue: Wrapped { return self ?? Wrapped.defaultValue }
}

This way you can extend your types very easily:

extension Int: Defaultable {
    static var defaultValue: Int { return 0 }
}

extension String: Defaultable {
    static var defaultValue: String { return "" }
}

extension Array: Defaultable {
    static var defaultValue: Array<Element> { return [] }
}

And usage goes like this:

let optionalInt: Int? = 10 // Optional(10)
let unwrappedInt = optionalInt.unwrappedValue // 10

let optionalString: String? = "Hello" // Optional("Hello")
let unwrappedString = optionalString.unwrappedValue // "Hello"

let optionalArray: [Int]? = nil // nil
let unwrappedArray = optionalArray.unwrappedValue // []
like image 144
Benno Kress Avatar answered Feb 21 '26 14:02

Benno Kress