Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

Literal Convertibles in Swift

Thursday — April 28th, 2016

Previously, I wrote about how handy the CustomStringConvertible protocol can be. The standard library is full of neat little protocols like this. If you scroll through the list you might notice quite a few protocols with the suffix “LiteralConvertible”.

Alfa spider

Literal Convertible Protocols allow you to maneuver your types in some pretty fun ways. The short gist is that you can turn a literal value into your custom type. Let’s start with IntegerLiteralConvertible. I’ll make a custom type called StarRating that I could use to get the rating of anything (apps, movies, restaurants, people, etc.). I want to be able to set it from and Int and be able to print out accordingly so I’ll have it implement IntegerLiteralConvertible and CustomStringConvertible:

struct StarRating: CustomStringConvertible, IntegerLiteralConvertible {
    let numberOfStars: Int

    var description: String {
        let star = Character("⭐")
        return String(count:numberOfStars, repeatedValue: star)
    }

    init(integerLiteral value: Int) {
        self.numberOfStars = value
    }
}

Now I can set a StarRating from an integer value directly and then print it out to my custom string:

let myRating: StarRating = 4
print(myRating)    // "⭐⭐⭐⭐"