001-枚举
//枚举 swift 中不会被赋于默认的整型值 enum someEnumeration { case north case sourth case east case west } //多个成员值要写在一行,用逗号隔开 enum Planet { case mercury,earth,mars } var directionHead = someEnumeration.west directionHead = .east //使用Switch匹配单个的枚举值 switch directionHead { case .north: print("north") case .sourth: print("sourth") case .west: print("west") case .east: print("east") default: print("None Of This Direction") }
//枚举关联值
enum BarCode { case upc(Int,Int,Int,Int) //根据数字识别商品 case qrCode(String) //根据代码识别商品 } //创建一个条形码 var productBar = BarCode.upc(8, 8, 3, 4) productBar = .qrCode("ABCDE")//upc被qrCode代替
//枚举原始值
//枚举的原始值 隐士赋值 enum ASCIIControlChar : Character { case tab = " " case lineFeed = " " case carriageReturn = " " } //字符串的默认值是枚举值本身 enum Planet:Int{ case mercury = 1,venus,earth,mars } //获取枚举变量的原始值 let earthOrder = Planet.earth.rawValue print(earthOrder)//输出结果为 3
//枚举递归
//枚举递归 indirect enum Arithmetic { case number(Int) case addition(Arithmetic,Arithmetic) case multiplication (Arithmetic,Arithmetic) } //创建一个枚举递归表达式 let five = Arithmetic.number(5) let four = Arithmetic.number(4) let sum = Arithmetic.addition(five, four) let product = Arithmetic.multiplication(sum, five) // (5+4) * 5 print(product)
//类
//类的声明: class Student{ var name:String = "" var age:Int = 18 } //访问属性 classItem.name = "小子" print(classItem.name)//小子
//结构体:
//结构体 struct teacher { var name:String = "" var age:Int = 20 } let myTeacher = teacher() print(myTeacher)//teacher(name: "", age: 20)
属性:
//存储属性 (变量和常量) class Student { var name:String = "" var age:Int = 10 } class newClass { //lazy var name = "小名" //懒加载属性 var lastName = "小小" var firstName = "苏" var name:String{ get { return firstName + lastName } } } class StepCount { var examplePro:Int = 10 { willSet (newTotal){ //在属性更改之前做的操作 print("新值是(newTotal)") } didSet { //在属性更改之后做的操作 print("新值-旧值(examplePro-oldValue)") } } }
//调用:
var allName = newClass() print(allName.name) //苏小小 //只读属性只能用var来描述 let stepCount = StepCount() stepCount.examplePro = 200 //新值是200 //新值-旧值190