Swift 集合类

Swift 集合类,第1张

概述Swift包含三种集合类 数组 Array 字典 Dictionary 集合 Set 数组 // 数组的声明 (调用数组的构造函数)var numbers:[Int] = [1,2,3,4]var strings:[String] = ["one","two","three","four"]// 空数组的声明var emptyArray1:[Int] = []var emptyArra

Swift包含三种集合类

数组 Array 字典 Dictionary 集合 Set 数组
// 数组的声明 (调用数组的构造函数)var numbers:[Int] = [1,2,3,4]var strings:[String] = ["one","two","three","four"]// 空数组的声明var emptyArray1:[Int] = []var emptyArray2 = [Int]()var emptyArray3 = Array<Int>()var emptyArray4:[String] = []var allZero = [Int](repeatElement(0,count: 5))allZero.count // 数量allZero.isEmpty // 是否为空allZero[2] // 去下标值allZero.first // 第一个元素allZero.last // 最后一个元素numbers[1..<3] // 取子数组numbers.min() //最小值numbers.max() //最大值strings.max() //String 排序有点蒙strings.min()strings.contains("one") // 是否包含元素strings.contains("five")strings.index(of: "one") // 元素在数组的位置strings.index(of: "two") // 元素在数组的位置strings.index(of: "five") // 返回的是一个可选型if let firstValue = allZero.first {    print("the first value is " + String(firstValue))}

数组的增 删 改
var strings:[String] = ["one","four"]// 改strings[0] = "1"strings[1...3] = ["2","3","4"]// 增strings.append("five")strings += ["six"]strings.insert("seven",at: 3)// 删strings.removeLast()strings.removeFirst()strings.remove(at: 2)strings.removeSubrange(0..<1)strings.removeAll()



数组的遍历
// 数组的声明 (调用数组的构造函数)var numbers:[Int] = [1,"four"]for number in numbers {    print(number)}for index in 0..<numbers.count {    print(numbers[index])}for (i,number) in numbers.enumerated() {    print("i is " + String(i) + " value is " + String(number))

字典的增删改查
var dict = ["key":"value","key1":"value1"]var dict1 = ["key":"value","key1":1] as [String : Any]var dict2:Dictionary<String,Any> = ["key":"value","key1":"value1"]var dict3:[String:Any] = ["key":"value","key1":"value1"]dict.countdict.isEmptyArray(dict1.values)Array(dict.keys)// 改dict["key"] = "value0"dict.updateValue("value0",forKey: "key")// 增dict["key3"] = "value3"dict.updateValue("value4",forKey: "key4")//删dict.removeValue(forKey: "key4")dict["key"] = nildict.removeAll()for key in dict.keys {    print(key)}for (key,value) in dict {    print("\(key):\(value)")}
总结

以上是内存溢出为你收集整理的Swift 集合类全部内容,希望文章能够帮你解决Swift 集合类所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1066832.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存