Weekly Swift articles, podcasts and tips by John Sundell.

Defaults for associated types

Published on 17 May 2018
Basics article available: Protocols

Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).

protocol Identifiable {
    associatedtype RawIdentifier: Codable = String

    var id: Identifier<Self> { get }
}

struct User: Identifiable {
    let id: Identifier<User>
    let name: String
}

struct Group: Identifiable {
    typealias RawIdentifier = Int

    let id: Identifier<Group>
    let name: String
}

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.