Grant Emerson

Literally Amazing

Literally Amazing — SwiftMoji Entry #24

Swift, like all other programming languages, provides a set of literals — textual expressions for representing values in code. For example, in the following code, “Bob” is a String literal and 5.5 is a Floating-Point literal. Swift also provides some special literals that start with a #. The #function literal returns a String containing the name of the enclosing declaration. This can be useful for providing default implementations for IDs or other String properties not seen by the user. For example, in the following code, the 👤 struct has a name and a height. It also provides an id property so that it can be used with other APIs that require conformance to the Identifiable protocol. The id is computed upon initialization to be the name of the enclosing declaration (👤) joined with a static running count of people created.

struct 👤: Identifiable {
    static var peopleCount = 0
    
    let name: String
    let height: Float
    
    var id: String = {
        Self.peopleCount += 1
        return "\(#function) \(Self.peopleCount)"
    }()
}

var 👨🏻 = 👤(name: "Bob", height: 5.5)
print(👨🏻.id) // 👤 1
Tagged with: