上代码
1.定义数组
func definitionArr()->(){
#if false
var arr:[Any] = []//空 任意类型
var arr1:[String] = []//空 只能存字符串
var arr2:[Any] = ["1",1]
var arr4:[Dictionary] = []
let arr3 = ["1",2] as Any
#endif
}
2.删除数组元素
func remove() -> () {
var arr = ["今","天","是","个","好","日","子","A","b"]
//删除指定index的元素
//arr.remove(at: 2)
//删除最后的一个元素
//arr.removeLast()
//删除最前的一个元素
//arr.removeFirst()
//单侧删除
//arr.removeFirst(3)
//单侧删除
//arr.removeLast(3)
//删除所有的元素
//arr.removeAll()
//是否保留arr的空间
arr.removeAll(keepingCapacity: true)
print(arr)
}
3.插入
func insertElement() -> () {
var arr = ["今","天","是","个","好","日","子","A","b"]
//插入数据
arr.insert("1", at: 0)
//print(arr)
}
4.添加元素
func addElement() -> () {
let arr1 = ["今","天","是","个","好","日","子"]
var arr = ["今","天","是","个","好","日","子","A","b"]
//添加数组
arr.append(contentsOf: arr1)
//print(arr)
}
5.数组去重
func arrRemovingWeight() -> () {
//数组去重
#if false
//方法1
let array = [111, 222, 111]
var dictInts = Dictionary<String, Int>()
for number in array {
dictInts[String(number)] = number
}
var result = [Int]()
for value in dictInts.values {
result.append(value)
}
print(result)
#endif
#if false
//方法2
let arr = ["1","2","3","4","3"]
var arr1:[String] = []
for item in arr {
if !arr1.contains(item){
arr1.append(item)
}
}
print(arr1)
#endif
//数组合并 只要不同的和只要相同的只需要在if的位置加判断即可
let arr = ["1","2","3","4"]
var arr1 = ["1","2","4","8"]
for item in arr {
if !arr1.contains(item){
arr1.append(item)
}
}
//print(arr1)
//判断数组是否为空
if arr1.isEmpty {
}
}
5.0数组的其他用法
func arrOterMethed() -> () {
//数组的其他用法
//删除数组
let arr = ["1","2","4","8"]
var arr1 = ["1","2","4","8"]
arr1.remove(at: 0)
//删除指定的元素
if arr1.contains("2") {
let index = arr1.index(of: "2")
arr1.remove(at: index!)
}
//使用数据
arr1[0] = arr[3]
print(arr1)
//数组降序
var arr3 = [2,4,1,6,9,5,4,9]
let count = arr3.count
var arr5:[Int] = []
let mix = arr3.min()
let max = arr3.max()
for _ in 0..<count {
arr5.append(disposeData(arr: arr3))
let index = arr3.index(of: arr3.max()!)
arr3 .remove(at: index!)
}
print(String(describing: arr5))
print("最大:\(String(describing: max))最小值:\(String(describing: mix))")
//数组存数组套字典
let arr4:Array<Array<Dictionary<String,String>>> = [[["name":"董"]]]
let arr6:Array<Dictionary> = arr4[0]
let dict:Dictionary = arr6[0]
print(dict["name"]!)
//数组的降序
let usernames = ["Lves", "Wildcat", "Lecoding","Cc"]
//数组的升序
let arr9:Array<String> = ["name","aler","ved","red","whie","pokm"]
let arr8:Array<String> = arr9.reversed()
print(arr8)
let resultName1 = usernames.sorted(by: backWards)
//数组的容量类似于count
let resultName2 = usernames.capacity
let user = ["Lves", "Wildcat", "Cc", "Lecoding"]
//用来判断两个队列的是否拥有相同的元素,并且顺序是一致的
let resultName3 = usernames.elementsEqual(user)
//判断两个数组是否一样并且顺序是一致的
let re = usernames.starts(with: user)
print(resultName1,re)
}
func backWards(s1: String, s2: String) -> Bool
{
return s1 > s2
}
func disposeData(arr :Array<Any>) -> Int {
let arr1:[Int] = arr as! [Int]
let max = arr1.max()
return max!
}