7.15
變量與常量
程序:計算機(jī)能理解的指令列表
變量:內(nèi)容可以修改
var bianliang = 123
bianliang = 234
常量:內(nèi)容不可以修改
let changliang = 123
寫程序不能有歧義
數(shù)據(jù)類型 Int UInt String Float/Double
類型轉(zhuǎn)換
iVal = Int(conVal)
iVal = "\(conVal)"
數(shù)據(jù)類型與集合類型
值類型與引用類型的區(qū)別
- 值類型
struct Animal {var name: String
var weight: Float}
var ani1 = Animal(name: "Cat", weight: 12)
var ani2 = ani1
ani1.name = "kitty"
修改了ani1.name,但是ani2.name不會變化
- 引用類型
class Animal {var name: String = "Cat"
var weight: Float = 12}
var ani1 = Animal()
var ani2 = ani1
ani1.name = "kitty"
雖然修改了ani1.name,但是ani2.name也會變
數(shù)組
var shuzu1 = [1, 2, 3, 4]
var shuzu2: [Int] = [1, 2, 3, 4]
var shuzu3 = [Int]_()
var shuzu4 = Array<Int>()
var shuzu5: Array<Int> = [1, 2, 3, 4]
var定義的數(shù)據(jù)可以修改內(nèi)容收恢,let定義的數(shù)組不可以修改內(nèi)容
shuzu1.count #獲取元素個數(shù)
shuzu1.append(5) #在末尾添加元素
shuzu1.append(contentsOf: [6, 7])
shuzu1.insert(8, at: 7) #在任意位置插入元素
shuzu1.insert(contentsOf: [9, 10], at: 0)
shuzu1.remove(at: 0) #移除元素
shuzu1.first #數(shù)組的首
shuzu1.last #數(shù)組的尾
shuzu1.removeLast()
shuzu1.removeFirst()
shuzu1.removeAll() #移除數(shù)組內(nèi)的所有元素
字典
字典的創(chuàng)建方式
var zidian1 = ["key1":12, "key2":45]
var zidian2: [String:Int] = ["key1":12]
var zidian3 = [String:Int]()
var zidian4: Dictionary<String, Int>
var zidian5 = Dictionary<String, Int>()
字典的可用操作
zidian1["key1"] = 56 #修改key1的值
zidian1["key3"] = 78 #若是沒有key3车胡,創(chuàng)建賦值
zidian.removeValue(forKey: "key1")
zidian.renmoveall