美文网首页
Swift Collection Types

Swift Collection Types

作者: YasuoYuHao | 来源:发表于2017-03-09 00:19 被阅读10次

    Collection Types

    Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

    Collection TypesCollection Types

    Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake. It also means you can be confident about the type of values you will retrieve from a collection.

    Creating an Empty Array
    You can create an empty array of a certain type using initializer syntax:

    var someInts = [Int]()
    
    print("someInts is of type [Int] with \(someInts.count) items.")
    
    // Prints "someInts is of type [Int] with 0 items."
    

    Creating an Array with a Default Value

    Swift’s Array
    type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer a default value of the appropriate type (called repeating): and the number of times that value is repeated in the new array (called count):

    var threeDoubles = Array(repeating: 0.0, count: 3)
    
    // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
    
    

    Creating an Array by Adding Two Arrays Together

    You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array’s type is inferred from the type of the two arrays you add together:

    相关文章

      网友评论

          本文标题:Swift Collection Types

          本文链接:https://www.haomeiwen.com/subject/bywbpttx.html