Swift Collection Types

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 Types
Collection 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:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,492评论 0 23
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 12,872评论 0 6
  • 不知道写下这样的题目,是否是合适。但我知道,前些天简友文章所言的那样,如果一个人在30岁,还有没有什么成就!那...
    weir_will阅读 1,081评论 0 0
  • 本书精髓:如何利用规律和趋势放大个人努力。从这本书可以得到成为高手的思维模式和方法,并且找到最佳的路径。 这个时代...
    步履如菲阅读 3,865评论 0 52
  • 文//夏玫小墨 我从来没有参加过演讲,最近公司组织了演讲比赛,顺利地进入了决赛,让我欢喜让我忧。 我紧张,我忐忑,...
    夏玫小墨阅读 2,394评论 0 1

友情链接更多精彩内容