枚举的基本用法
swift 中通过enum关键字声明一个枚举
enum MREnum{
case test_one
case test_two
case test_three
}
上面的写法也可以变成如下
enum MREnum{
case test_one,test_two,test_three
}
OC中,枚举默认是整形,如下A,B,C默认代表0,1,2
typedef NS_ENUM(NSInteger,MrEnum){
A,
B,
C
}
swift中枚举更加的灵活,并且不需要给枚举中的每一个成员都提供值,如果一个值(所谓的原始“值”)要被提供给每一个枚举成员,那么这个值可以是字符串,字符,任意的整数值,或者是浮点数
enum Color:String{
case red = "Red"
case amber = "Amber"
case green = "Green"
}
enum MrEnum: Double{
case a = 10.0
case b = 11.0
case c = 12.0
}
隐式RawValue分配时建立在swift的类型推断机制上的
enum DayOfWeek:Int {
case mon,tue,wed,thu,fri = 10,sat,sun
}
print(DayOfWeek.mon.rawValue) // 0
print(DayOfWeek.fri.rawValue) // 10
print(DayOfWeek.sat.rawValue) // 11
print()
如果类型推导不正确,编译器不通过
关联值
在swift中,枚举不能定义存储属性,但是我们可以使用关联值定义更加复杂的数据结构
enum Shape{
case circle(radious:Double)
case rectangle(width: Int,height: Int)
}
let shape = Shape.circle(radious:10.0)
switch shape{
case let .circle(radious):
print(radious)
case let .rectangle(width,height):
print("width:\(width),height:\(height)")
}
//也可以这么写 其中参数使用let还是var 根据实际需求确定
switch shape{
case .circle(let radious):
print("radious:\(radious)")
case .rectangle(var width,let height):
print("width:\(width),height:\(height)")
}
//如果不想匹配所有的case 使用defalut
switch shape{
case .circle(let radious):
print("radious:\(radious)")
default:
print("other")
}
optional
class MrTeacher{
var age:Int?
}
当前的age我们就称之为可选值,optional的本质是什么呢? 我们之间跳转到源码发现
@frozen public enum Optional<Wrapped>:ExpressibleByNilLiteral {
case none
case some(Wrapped)
}
可选链
我们知道在OC中我们给一个nil对象发送消息什么也不会发生,swift中我们是无法像一个nil发送消息的,但是可以借助可选链达到类似的效果
let str:String? = "124"
let upStr = str?.uppercased()
print(upStr) // Optional("123")
var str: String?
let upStr = str?.uppercased()
print(upStr) // nil
解包
//方法一
var str: String?
let str2 = "1"
let upStr = str?.uppercased()
if let value = upStr{
print(value)
}else{
print("nil upStr")
}
//方法二
guard let v = upStr else{
print("nil upStr")
return
}
print(v)
//guard后面可以跟多个语句,用,号隔开
guard let v = upStr,str2.count > 0 else{
print("nil upStr")
return
}
print(v)