Weekly Swift articles, podcasts and tips by John Sundell.

Creating a dedicated identifier type

Published on 07 May 2018
Basics article available: Protocols

If you want to avoid using plain strings as identifiers (which can increase both type safety and readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!

struct Identifier: Hashable {
    let string: String
}

extension Identifier: ExpressibleByStringLiteral {
    init(stringLiteral value: String) {
        string = value
    }
}

extension Identifier: CustomStringConvertible {
    var description: String {
        return string
    }
}

extension Identifier: Codable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(string)
    }
}

struct Article: Codable {
    let id: Identifier
    let title: String
}

let article = Article(id: "my-article", title: "Hello world!")

Support Swift by Sundell by checking out this sponsor:

Magic Lasso Adblock
Magic Lasso Adblock

Magic Lasso Adblock: Block ads, trackers and pop-ups on your iPhone, iPad and Mac. Magic Lasso Adblock provides a 2.0x speed increase on common websites, improves your privacy by removing ad trackers and works with Safari across all devices. It’s as if Apple themselves had designed an ad blocker. Download for free today.