Swift-类、结构体、枚举

001-枚举

//枚举 swift 中不会被赋于默认的整型值
enum someEnumeration {case northcase sourthcase eastcase west
}
//多个成员值要写在一行,用逗号隔开
enum Planet {case mercury,earth,mars
}
var directionHead = someEnumeration.westdirectionHead = .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 = "t"case lineFeed = "n"case carriageReturn = "r"
}
//字符串的默认值是枚举值本身
enum Planet:Int{case mercury = 1,venus,earth,mars
}
//获取枚举变量的原始值let earthOrder = Planet.earth.rawValueprint(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) * 5print(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

 

 

 

 

转载于:https://www.cnblogs.com/StevenHuSir/p/Swift_Enum.html

Published by

风君子

独自遨游何稽首 揭天掀地慰生平