swift小结 1

swift小结 1

变量命名规则及值类型说明

C/C++:

  1. 字母、数字、下划线
  2. 必须以字母、下划线开头
  3. 不能与关键字重名
  4. 一般需要容易识别

swift可以用UTF-8

var 学生 = "zhangsan" //String
var  = "Cow"
print(, 学生)  //输出:Cow zhangsan

值类型自动推导

Swift会根据变量或常量的初始值决定类型

var dVal = 23.4 //dVal是Double类型

显式说明类型

var iVal: Int = 23
let conVal: Double = 34.0

类型转换

iVal = Int(conVal)

Swift的字符串可以相加,就是字符串连接

var s: String = "iVal = " + String(iVal)
s = "iVal = \(iVal) \(conVal)" //插值
print(s)

数组、字典

数组可以容纳多个同一类型的值,可以通过下标取值;字典是键值对,通过key取值;数组和字典都是值类型

数组

//1. 使用var定义的数组为可变数组
var arr02: [String] = ["2", "3", "4"]
var arr03: Array = Array()

print(arr03)
arr03.append(12)  //在数组末尾添加元素
print(arr03[0])  //下标从0开始

var arr04 = arr03  //数组是值类型,赋值时发生复制,变成两个独立的空间
arr03[0] = 67
print(arr03)
print(arr04)

arr03 = arr03 + arr04 //数组加法是将两个数组合成一个(直接将arr04的元素有序插入arr03后面)

print(arr03)

arr03 = arr03.sort(>)
print("---", arr03)

//[67, 45]
arr03.insert(89, atIndex: 0) //在指定位置插入值
print(arr03.count, arr03)

arr03.removeAtIndex(0) //删除指定位置的值
print(arr03.first, arr03.last)
arr03.removeFirst()
print(arr03)
arr03.removeLast()
arr03.removeAll()

字典

//key:value, key是唯一的
var dict01 = ["班长":12,
              "小兵":34,
              "key3":45]
print(dict01["key3"])
dict01["key3"] = 45 //如果key存在,修改元素的值
print(dict01)

var dict02: Dictionary = Dictionary()
dict02["key4"] = 56  //如果key不存在,增加元素
print(dict02)

var dict03: [Int:Int] = [Int:Int]()
dict03[0] = 23
dict03[1] = 45
print(dict03.count)

类与结构体

类是引用类型,结构体是值类型。

struct Animal {
    var name: String
    var weight: Double
}

class AnimalClass {
    var name: String = "Cat"
    var weight: Double = 12.0
}

var ani01 = Animal(name: "Cat", weight: 12.0)
var ani02 = ani01  //ani01、ani02是值类型,空间直接复制

print(ani01.name, ani02.name)

ani01.name = "Kitty"
print(ani01.name, ani02.name) //ani01.name: Cat ani02.name: Kitty

var ani03 = AnimalClass(name: "Cat", weight: 12.0)
var ani04 = ani03 //ani01、ani02是引用类型,共用值空间

print(ani03.name, ani04.name)

ani01.name = "Kitty"
print(ani03.name, ani04.name) //ani03.name: Kitty ani04.name: Kitty

你可能感兴趣的:(swift小结 1)