• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Swift:枚举

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Enumerations in Swift are flexible, and do not have to provide a value for each case of the enumeration. If a value(known as "raw" value) if provied for each enumeration case, the value can be a string, a character, or a value of any integer for floating-point type.

枚举的语法

enum CompassPoint {
	case north
	case south
	case east
	case west
}

多个case可以写在一行,用逗号分隔

enum Planet {
	case mercuy, venus, earth, mars, jupiter, saturn, uranus, neptune
}

简单使用

var directionToHead = CompassPoint.west

directionToHead = .east

关联值(Associated Values)

enum Barcode {
	case upc(Int, Int, Int, Int)
	case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

提取关联的值:

switch productBarcode {
case .upc(let numberSystem, let manufacturer, var product, let check):
    break
case .qrCode(let productCode):
    break
}

如果关联的值都要提取为常量或者都要提取为变量,可以这样写:

switch productBarcode {
case let .upc(numberSytem, manufacturer, product, check):
    break
case let .qrCode(productCode):
    break
}

Raw Values

//raw value可以是字符串、字符、任何整型、浮点型
enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

Implicitly Assigned Raw Values

当你使用枚举存储整型或者字符串类型的raw value时,没有必要给每一个case赋值。整型从0开始,字符串的raw value是case的名字。

enum RefinementPlanet: Int {
    case mercury = 1, vanus, earth, mars, jupiter, saturn, uranus, neptune
}

enum RefinementCompassPoint: String {
    case north, south, east, west
}
let earthsOrder = Planet.earth.rawValue
// earthsOrder is 3
 
let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Initializing from a Raw Value

If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called rawValue) and returns either an enumeration case or nil.

let possiblePlanet = RefinementPlanet(rawValue: 7)
//possiblePlanet的类型是 RefinementPlanet?

Recursive Enumerations

递归枚举是一个枚举的一个或者多个case使用另一个枚举的实例作为关联值。通过的case前写indirect来表示这个case是递归的。

enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap