美文网首页
Swift 基本语法(四)— 集合类型

Swift 基本语法(四)— 集合类型

作者: Eddiegooo | 来源:发表于2019-10-04 11:17 被阅读0次

集合 数组 字典

数组
let array: Array<Int> = []  //初始化空数组必须指定类型
var array1 = [1, 2, 3, 4]
array1 = []  //这时候可以根据上文推断出array类型

let array2 = Array(repeatElement(5, count: 3))
print(array2) //[5, 5, 5]

let chars = Array("Chars")
print(chars)

let array3 = Array(1...5)
print(array3)

let person = ["name" : "Eddiegooo", "age" : 30, "sex" : "male"] as [String : Any]
let keyArray = Array(person.keys)
print(keyArray)

** 数组遍历方式:for in, 和 forEach; forEach有两个特征:1.无法使用break 或 continue跳出跳过循环 2.使用return只是跳出本次循环**

let array = [Int](2...7)
for num in array {
    print(num)
}
array.forEach { (num) in
    if num == 3{
        return //跳过num=3的那个循环,后面循环会继续执行。  break continue这里是不合法的
    }
    print(num)
}
for i in 0..<array.count {
    print(array[i])
}
for i in array.indices {
    print(array[i])
}
var index = array.makeIterator()
while let num = index.next() {
    print(num)
}
//直接获取index 和 value
for (index, value) in array.enumerated() {
    print("array index = \(index), value = \(value)")
}

索引判断

let array = [10, 20, 5, 30, 101, 50, 8]
//是否包含某个元素
array.contains(5)
array.contains { (num) -> Bool in
    num < 20
}
print(array.contains(where: { $0 == 30 }))
array.allSatisfy({ $0 > 3})  //是否所有元素都符合要求

array.first
array.last
print(array.first(where: { $0 > 30 })) //第一个大于30的值:  Optional(101)  可选值类型. last 同样也有,返回从后面开始第一个符合条件的值
array.firstIndex(of: 20)   //获取第一个值为20的索引 同理也有lastIndex
array.firstIndex(where: { $0 > 20})  //获取符合条件的第一个索引
array.min()
array.max()
//获取符合条件的最大最小值
let errorArray = [(101, "errorFail"), (404, "Not Found"), (303, "transfer")]
errorArray.min { (a, b) -> Bool in
    a.0 > b.0
}
errorArray.max { (a, b) -> Bool in
    a.1 < b.1
}

数组操作

//数组操作
var array = [Int](2...7)
array.append(1)
array.append(contentsOf: 15..<19)
array.insert(1, at: 0)
array.insert(contentsOf: (101...102), at: 3)

array.remove(at: 1)
array.removeFirst()
array.removeFirst(2) //移除前两个元素
array.removeLast(3) //移除后三个元素

array.removeLast() //数组不可以为空
array.popLast() //这时数组可以为空

array.removeSubrange(1...3) //移除某个区间的元素
array.removeAll()
array.removeAll(keepingCapacity: true) //移除数组所有元素,但是会保留数组容量
数组切片
//ArraySlice 数组切片,会远数组公用同一块内存。 但是它们两个是两个完全不同的,相互独立的,互不影响
var numbers = [2,5,67,20,8,23,9]
var slice = numbers.dropFirst()
//numbers = slice   这里会报错,因为它们是两个类型
numbers = Array(slice)  //将slice转换成数组

slice = numbers.drop(while: { (num) -> Bool in
    num < 10  //当第一个符合条件的值,就直接获取了 [67, 20, 8, 23, 9]
})

slice = numbers.prefix(5)
slice = numbers.prefix(upTo: slice.count - 2) //这里也不能数组越界哦

slice = numbers.suffix(3)
slice = numbers.suffix(from: 5)

slice = numbers[1...3]
slice = numbers[...5]
slice = numbers[2...]

numbers.append(contentsOf: 33...35) //数组添加值, 不影响slice的值。
slice.append(contentsOf: 44...45)

数组排序拼接

// 数组排序
var numbers = [2, 44, 52, 7, 9, 10, 30, 53]
let numbers1 = [2, 44, 52, 7, 9, 10, 30, 53]

//numbers.shuffle()  //在原数组上随机化数组
//numbers1.shuffled()  //不会改变原数组,返回一个新的随机化的数组。  可以用于let 数组

numbers.reverse()  //原数组上逆序排列
numbers1.reversed()  //可作用于常量、变量数组的逆序排列

//将数组分成两个切片, 符合条件的在前面,不符合的在后面一个集合.  不稳定排序
numbers.partition(by: { $0 > 30 })
let index = numbers.partition { (num) -> Bool in
    num > 20
}
let slice = numbers[..<index]
let slice2 = numbers[index...]

numbers.sort()
numbers1.sorted()

numbers.swapAt(numbers.startIndex, numbers.endIndex - 1) //交互两个位置的值
//数组拼接操作 只能对个别几种类型拼接 也就是只能Sequence类型拼接
//字符串数组拼接
var array = ["Hello", "World"]
array.joined()  //HelloWorld
array.joined(separator: ",")  //Hello,World
//区间。 数组里包含数组。   元组类型不可以拼接
let rangs = [1...3, 5...9, 15...17]
for i in rangs.joined() {
    print(i)  //这样子可以得到所有的元素
}

数组应用

//使用数据实现一个栈 队列同理。。
struct Stack<T> {
    private var elements = [T]()
    
    var count: Int {
        return elements.count
    }
    
    var isEmpty: Bool {
        return elements.isEmpty
    }
    
    mutating func push(_ element: T) {
        elements.append(element)
    }
    
    mutating func pop() -> T? {
        return elements.popLast()//可以作用于空数组 没问题
//        return isEmpty ? nil : elements.removeFirst() //队列移除第一个元素,要做判空处理
    }
}
Set 集合。 确定性 互斥性 无序性
//集合  无序性。  如果不指定类型 这就是数组了
let course = ["math", "chinese", "english"]  //此时就是数组
let courseSet: Set<String> = ["math", "chinese", "english"] //指定set集合类型,这时就是集合了

var courseSets = Set<String>()
courseSets.insert("English")

//集合类型必须是可hash 的。
struct Person {
    var name: String
    var age: Int
}
let personSet: Set<Person> = [Person(name: "Eddiegooo", age: 30)]  //直接这样写会报错,set要是可哈希的,error: type 'Person' does not conform to protocol 'Hashable'
extension Person: Hashable {
    //实现Hashble方法, 遵循了Hashble协议
}
let personSet: Set<Person> = [Person(name: "Eddiegooo", age: 30)]   //这样子就可以了

集合操作。 和数组类似

var courseSet: Set<String> = ["math", "chinese", "english"]
for course in courseSet {
    print(course)
}
//有序遍历
for course in courseSet.sorted() {
    print(course)
}

extension Person: Equatable {
  static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.name == rhs.name
    }
}
//集合有一个update方法。  之前没有就新增,之前已经有了,就更新
courseSet.update(with: "history")
//插入 inset   移除remove 方法都和数组类似
courseSet.insert("aaa")
courseSet.removeFirst()  //这个第一元素是指 集合hash第一个值,不一定是第一个元素。 因为集合是无序的
courseSet.remove("test")  //是不存在的集合值也可以
//courseSet.removeAll(keepingCapacity: true)
//筛选方法 filter.  会将符合条件的集合筛选出来
courseSet.filter(<#T##isIncluded: (String) throws -> Bool##(String) throws -> Bool#>)

集合判断

let courseSet: Set<String> = ["math", "chinese", "english"] 
let customSet: Set = ["Math", "Chinese", "english"]
courseSet.intersection(customSet) //交集
courseSet.union(customSet) //并集
courseSet.symmetricDifference(customSet)//对称差集
courseSet.subtracting(customSet) //相对补集
//还有对应的是否是什么集合的判断方法
customSet.isSubset(of: customSet)
customSet.isStrictSubset(of: customSet) //超集
customSet.isSuperset(of: customSet)
customSet.isDisjoint(with: customSet) //是否有公共元素
字典Dictionary
//字典Dictionary
let dict = Dictionary<String, Int>()
let dict1 = [String : Int]()
let dict2: Dictionary<String, Int> = [:]
var dict3: [String : Any] = ["name" : "Eddiegooo", "age" : 30, "sex" : "male"]
var dict4 = ["name" : "Chole", "age" : "30", "sex" : "female"]
for (index, value) in dict3 {
    print(index, value)
}
dict4["name"] = "Eddie's wife" //更新某一个值。
dict4["name"] = nil //直接将键置为nil, 就删除了这个元素
dict4.updateValue("Chole", forKey: "name") //更新某个键值。
//合并两个字典。
//merge 会直接改变原来字典的值
dict3.merge(dict4) { (_, current) -> Any in
    current
}
//merging 不会改变原来字典的值
let newDict = dict3.merging(["a" : "34"]) { (_, new) -> Any in
    new
}
print(newDict)
//有序字典  KeyValuePairs.  和填入到字典的顺序一致
let kvs: KeyValuePairs = ["a" : 1, "c" : 3, "b" : "2"]
print(kvs)  //["a" : 1, "c" : 3, "b" : "2"]
//字典其它操作参考数组 集合。

相关文章

  • Swift 基本语法(四)— 集合类型

    集合 数组 字典 数组 ** 数组遍历方式:for in, 和 forEach; forEach有两个特征:1...

  • Swift基本语法之函数

    Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本语法之循环 Swift...

  • Swift基本语法之数组和字典

    Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本语法之循环 Swift...

  • Swift基本语法之元组和可选类型

    Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本语法之循环 Swift...

  • Swift基本语法之闭包

    Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本语法之循环 Swift...

  • Swift基本语法之类的使用

    Swift中类的使用 Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本...

  • Swift基本语法之字符串

    Swift基本语法之初体验-常量变量-数据类型 Swift基本语法之逻辑分支 Swift基本语法之循环 字符串的介...

  • Swift -- 集合类型

    Swift 集合类型 Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存...

  • Swift语法--集合类型

    集合类型 提供三种集合,数组、合集、字典。Swift中的集合总是明确能储存的值的类型。 Swift中的集合是采用泛...

  • 4、Swift集合类型

    集合类型 Swift 语言提供数组(Array)、集合(Set)和字典(Dictionary)三种基本的集合类型用...

网友评论

      本文标题:Swift 基本语法(四)— 集合类型

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