print("数组字典")
//数组:Array
var a1: [Int] = []
if a1.isEmpty {
print("数组为空")
a1 = [1,2,3,4,5]
}
//长度计算
print(a1.count)
//添加元素
a1 += [6]
a1.append(7)
a1.insert(8,at: 0)
print(a1)
//删除
//删除第一个
a1.removeFirst()
//删除前几个
a1.removeFirst(2)
//删除指定索引的元素
a1.remove(at: 3)
//删除最后一个
a1.removeLast()
//删除所有
a1.removeAll()
print(a1)
var a2 = ["one","two","three","four"]
//修改指定索引的元素
a2[0] = "ling"
a2[1...3] = ["er","san","si"]
print(a2)
//是否包含元素
print(a2.contains("two"))
//遍历数组
for ele in a2 {
print(ele)
}
for (index,value) in a2.enumerated() {
print("a2[\(index)] = \(value)")
}
//var array: NSArray = [123,456]
//字典:Dictionary
var d1:[Int: String] = [1:"one",2:"two"]
//添加元素
d1[3] = "three"
d1.updateValue("four",forKey: 4)
print(d1)
//删除元素
d1.removeValue(forKey: 1)
//d1.removeAll()
//所有键
for key in d1.keys {
print(key)
}
for value in d1.values {
print(value)
}
//遍历字典
for (key,value) in d1 {
print("\(key):\(value)")
}
var aaa: NSMutableArray = []
aaa.add("abc")
aaa.add(250)
#if true
//将获取的元素强制转换为String类型,若能够则转换成功
var bbb: String = aaa[0] as! String
#else
//若不能转换成功,则会出现崩溃
var bbb: String = aaa[1] as! String
#endif
print(bbb)
#if false
//将获取的元素转换为Int?类型,若能够则转换成功
var ccc: Int? = aaa[1] as? Int
//若不能转换成功,则返回nil
var ccc: Int? = aaa[0] as? Int
print(ccc)
原文链接:https://www.f2er.com/swift/321708.html