Swift--09枚举类型

前端之家收集整理的这篇文章主要介绍了Swift--09枚举类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//声明枚举类型

enum Direction {

#if false

case north

case south

case east

case west

#else

case north,south,east,west

#endif

}


//初始化未指明类型时需要:类型.枚举值

var dir = Direction.east

//当变量类型已知时无需写类型:.枚举值

dir = .east //

var dir2: Direction = .south


switch dir {

case .north:

print("")

case .south:

print("")

case .east:

print("")

case .west:

print("西")

}


//原始值

enum Week: Int {

case monday = 100,tuesday,wednesday,thursday,friday,saturday,sunday

}


//在没有指定枚举值使用的数据类型时,无法获取原始值

print(Week.friday.rawValue)//104


//将一个原始值转换枚举变量,会得到一个可选类型的变量(因为可能会失败)

let dayOne = Week(rawValue: 102)

if let day = dayOne {

print(day)//wednesday

}


//枚举关联值

enum Point {

case start(x: Double,y: Double)

case end(x: Double,y: Double)

case center(x: Double,y: Double)

}


var point = Point.start(x: 0,y: 0)

point = .end(x: 10,y: 10)

point = .center(x: 5,y: 5)


switch point {

case .start(let x,let y):

print("起点(\(x),\(y))")

case .end(let x,19)"> print("终点(\(x),\(y))")

case .center(let x,19)"> print("中点(\(x),\(y))")

}

原文链接:https://www.f2er.com/swift/321702.html

猜你在找的Swift相关文章