7.15

96
zhujian6
2016.07.15 20:37* 字数 211

7.15

变量与常量

程序:计算机能理解的指令列表

变量:内容可以修改

var bianliang = 123

bianliang = 234

常量:内容不可以修改

let changliang = 123

写程序不能有歧义

数据类型 Int UInt String Float/Double

类型转换

iVal = Int(conVal)
iVal = "\(conVal)"

数据类型与集合类型

值类型与引用类型的区别

  1. 值类型

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不会变化

  1. 引用类型

class Animal {var name: String = "Cat"
var weight: Float = 12}
var ani1 = Animal()
var ani2 = ani1
ani1.name = "kitty"

虽然修改了ani1.name,但是ani2.name也会变

数组

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定义的数据可以修改内容,let定义的数组不可以修改内容

shuzu1.count                     #获取元素个数

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                     #数组的首

shuzu1.last                      #数组的尾

shuzu1.removeLast()

shuzu1.removeFirst()

shuzu1.removeAll()               #移除数组内的所有元素

字典

字典的创建方式

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,创建赋值

zidian.removeValue(forKey: "key1")

zidian.renmoveall
随笔