waltcow / blog

A personal blog
21 stars 2 forks source link

swift4语法备忘-Subscripts #32

Open waltcow opened 6 years ago

waltcow commented 6 years ago

Subscripts

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection. For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key].

You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.

Syntax

subscript(index: Int) -> Int {
    get {
        // return an appropriate subscript value here
    }
    set(newValue) {
        // perform a suitable setting action here
    }
}

//read-only computed properties
subscript(index: Int) -> Int {
    // return an appropriate subscript value here
}