Subscript in Swift

By implementing Subscript we can set and retrieve structure value by index (associative array or dictionary style) without separate methods for setting and retrieval. Classes and Enumerations can define subscripts too.

For example, I want to build an Address struct that can hold different string values. A contact can have a present address and a permanent address.

public struct Address {
    public var presentAddress: String?
    public var permanentAddress: String?

    public init() {

    }
}

var address = Address()
address.presentAddress = "Present Address"
address.permanentAddress = "Permanent Address"

print(address.presentAddress)
print(address.permanentAddress)

Without the subscript the Address has limited two members, presentAddress and permanentAddress. If we implement subscript we can have more than two addresses.


public struct Address {
    private var members: Dictionary<String, String> = [:]
    
    public init() {
    }
    
    public subscript(member: String) -> String {
        get {
            return members[member, default: "No value set"]
        }
        
        set(newValue) {
            members[member] = newValue
        }
    }
}

var address = Address()

address["presentAddress"] = "Present Address"
address["permanentAddress"] = "Permanent Address"
address["officeAddress"] = "Office Address"

print(address["presentAddress"])
print(address["permanentAddress"])
print(address["officeAddress"])

Spread the love

Leave a comment