在 Swift 编程语言中,数据结构和类型的合理运用对于高效编程至关重要。接下来,我们将深入探讨数组、集合、字典、区间、元组和可选类型的相关知识。
一、数组(Array)
(一)元素定义
可以通过多种方式定义数组,例如:
var a = [1,2,3]
var b = ["a","b","c"]
var c = [true,false,false]
也可以显式指定类型:
var a1:Array<Int> = [1,3,4]
var a2:[Int] = [1,2,3]
还可以通过其他方式创建数组,如:
var b1 = Array<Int>()
var b2 = Array<Int>([1,2,3])
var b3 = Array(1...3)
var c1 = Array(repeating: "*", count: 10)
(二)元素访问
通过索引访问数组元素:
print(a[0])
访问数组的子范围:
print(b[0...2])
print(b[...2])
print(b[1...])
(三)数组遍历
以下是几种常见的遍历数组的方式:
for item in b{print(item,terminator: "-")
}for(index,value) in b.enumerated(){print(index,value,terminator: "-")
}b.forEach{ item in print(item)}
(四)元素增删
对数组进行元素的添加和删除操作:
var fruit = ["青苹果","香蕉","芒果"]
fruit.append(b[0])
fruit.append(contentsOf: ["apple","orange"])
fruit += ["西红柿"]
fruit.insert("椰子", at: 1)
fruit.insert(contentsOf: ["a","b"], at: 0)fruit.removeFirst();
fruit.removeLast();
fruit.remove(at: 0)
fruit.removeSubrange(0...1)
(五)数组的变换
对数组进行一些变换操作,例如:
fruit.map{$0.uppercased()
}
(六)数组的方法
数组具有一些实用的方法,如:
print(c1.count) //长度
print(c1.isEmpty) //判空print(fruit.first?? "") //第一个元素
print(fruit.last?? "") //最后一个元素
print(fruit.randomElement()?? "") //随机访问num.sort() //排序
//升降
num.sort(by: >)
num.sort(by: <)
fruit.shuffle() //打乱//反转
var s1 = fruit.reversed();
fruit.reverse()
二、集合(Set)
(一)集合定义
var numSet:Set<Int> = [1,2,3]
var numSet2 = Set([1,2,3,4])var stringSet = Set(["苹果","蓝莓"])
(二)集合操作
集合的插入、更新、删除等操作:
var (m,n) = stringSet.insert("香蕉")
stringSet.update(with: "橘子")
stringSet.remove("苹果")
stringSet.removeAll();
集合的运算,如并集、差集、交集等:
print(numSet.union(numSet2))
print(numSet.subtracting(numSet2))
print(numSet.intersection(numSet2))
print(numSet.symmetricDifference(numSet2))
print(numSet.isSubset(of: numSet2))
print(numSet.isSuperset(of: numSet2))
三、字典(Dictionary)
(一)字典定义
var dict:Dictionary<Int,String> = [:]
var dict2:Dictionary<Int,String> = [1:"apple",2:"orange"]
var dict3 = ["张三":"李四"]
(二)字典遍历
通过不同方式遍历字典:
for (key,value) in dict2{print(key,value)
}for (key) in dict2.keys{print(key)
}for value in dict2.values{print(value)
}dict2.forEach{print($0,$1)
}
dict2.forEach{ (key,value) inprint(key,value)
}
四、区间(Range)
区间包括半开区间和闭区间等:
var a = 1...3
var b = "a"..."z"
var c =...100.0
var d = stride(from: 0, to: 10, by: 2)
五、元组(Tuple)
元组类似于其他语言中的元组结构:
var p = (1,"张三",10,"age","man")
var p2 = (id:1,name:"张三",age:10,unit:"age",sex:"man")
六、可选类型(Optional)
可选类型用于处理可能为空的值:
var i = Int("1")//Optional=可选类型print(type(of: i))//!代表解包 ,如果你确定存在就可以解包print(i!)var a:String?="project12"var b:Optional<Int> = 1var c:Int? = Optional.some(34)var d:Int? = Optional.noneprint(d == nil)//a为可选类型,后面会被加?print(a?.hasPrefix("project"))
七、源码
//
// array_study.swift
// StudySwift
//
// Created by YuJun on 2024/7/27.
//import Foundationfunc array_study(){//元素定义var a = [1,2,3]var b = ["a","b","c"]var c = [true,false,false]print(a,b,c)var a1:Array<Int> = [1,3,4]var a2:[Int] = [1,2,3]var b1 = Array<Int>()var b2 = Array<Int>([1,2,3])var b3 = Array(1...3)var c1 = Array(repeating: "*", count: 10)print(a1,a2,b1,b2,b3,c1)//元素访问print(a[0])print(b[0...2])print(b[...2])print(b[1...])//数组的遍历for item in b{print(item,terminator: "-")}for(index,value) in b.enumerated(){print(index,value,terminator: "-")}b.forEach{ item in print(item)}//元素增删var fruit = ["青苹果","香蕉","芒果"]fruit.append(b[0])fruit.append(contentsOf: ["apple","orange"])fruit += ["西红柿"]fruit.insert("椰子", at: 1)fruit.insert(contentsOf: ["a","b"], at: 0)fruit.removeFirst();fruit.removeLast();fruit.remove(at: 0)//删除区间元素fruit.removeSubrange(0...1)var num = [1,2,3]num.insert(contentsOf: 4...6, at: 2)print(num)//替换将01替换一下fruit.replaceSubrange(0...1, with: ["c","d"])num += (4...7)print(num)if(fruit.contains("西红柿")){print("yes")}else{print("no")}//这里必须使用$,var xihongshi = fruit.first(where: {$0=="西红柿"})var xihongshi2 = fruit.first(where: {n in n=="西红柿"})var xihongshi3 = fruit.firstIndex(where: {n in n=="西红柿"})print(xihongshi ?? "")print(xihongshi2 ?? "")print(xihongshi3 ?? -1)print(num.max())print(num.min())//数组的变换fruit.map{$0.uppercased()}print(fruit)//数组的一些方法print(c1.count)print(c1.isEmpty)print(fruit.first ?? "")print(fruit.last ?? "")//输出随机print(fruit.randomElement() ?? "")num.sort()num.sort(by: >)num.sort(by: <)//打乱fruit.shuffle()//反转var s1 = fruit.reversed();fruit.reverse()let line = "a a a+a"print(line.split(separator: " "))print(line.split(whereSeparator: {c in c == "+" || c == " "}))print(fruit.joined(separator: "-"))}//Set学习func set_study(){//集合Set的定义var numSet:Set<Int> = [1,2,3]var numSet2 = Set([1,2,3,4])var stringSet = Set(["苹果","蓝莓"])var (m,n) = stringSet.insert("香蕉")//若存在m=false,不存在m=true并插入print(m,n)var (p,q) = numSet.insert(1)stringSet.update(with: "橘子")//强行插入stringSet.remove("苹果")stringSet.removeAll();//Set的加减交子集合print(numSet.union(numSet2))//加print(numSet.subtracting(numSet2))//减print(numSet.intersection(numSet2))//交print(numSet.symmetricDifference(numSet2))//差print(numSet.isSubset(of: numSet2))//子print(numSet.isSuperset(of: numSet2))//超print(numSet.randomElement() ?? -1)//超//其他函数参考数组,遍历也是
}func dict_study(){var dict:Dictionary<Int,String> = [:] //空的字典,不写就是数组了var dict2:Dictionary<Int,String> = [1:"apple",2:"orange"] //空的字典print(type(of: dict))print(dict2)var dict3 = ["张三":"李四"]print(dict3["张三",default: ""])for (key,value) in dict2{print(key,value)}for (key) in dict2.keys{print(key)}for value in dict2.values{print(value)}dict2.forEach{print($0,$1)}dict2.forEach{ (key,value) inprint(key,value)}print(<#T##items: Any...##Any#>)//获取随机元素print(dict2.randomElement())
}//区间func range_study(){var a = 1...3var b = "a"..."z"var c = ...100.0var d = stride(from: 0, to: 10, by: 2)var e:Range<Int> = 1..<3var f:ClosedRange<Int> = 1...3//循环他们只有整数的闭合区间才能便利for g in a{print(g)}}//元组 类似于py的元组,实际元组并不存在
func yuan_study(){var p = (1,"张三",10,"age","man")var p2 = (id:1,name:"张三",age:10,unit:"age",sex:"man")print(p.0)print(p2.name)}//可选类型func emtry_study(){var i = Int("1")//Optional=可选类型print(type(of: i))//!代表解包 ,如果你确定存在就可以解包print(i!)var a:String?="project12"var b:Optional<Int> = 1var c:Int? = Optional.some(34)var d:Int? = Optional.noneprint(d == nil)//a为可选类型,后面会被加?print(a?.hasPrefix("project"))}
关注公众号:资小库,问题快速答疑解惑