加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift2 枚举类型

发布时间:2020-12-14 02:00:31 所属栏目:百科 来源:网络整理
导读:枚举语法 enum CompassPoint { case North case South case East case West}var directionToHead = CompassPoint.WestdirectionToHead = .South directionToHead的类型被推断当它被CompassPoint的一个可能值初始化。 一旦directionToHead被声明为一个Compass

枚举语法


enum CompassPoint {
    case North
    case South
    case East
    case West
}
var directionToHead = CompassPoint.West
directionToHead = .South

directionToHead的类型被推断当它被CompassPoint的一个可能值初始化。
一旦directionToHead被声明为一个CompassPoint,你可以使用更短的点(.)语法将其设置为另一个CompassPoint的值.


匹配枚举值


enum CompassPoint {
    case North
    case South
    case East
    case West
}
var directionToHead = CompassPoint.West

directionToHead = .South
switch directionToHead {
case .North:
    print("Lots of planets have a north")
case .South:
    print("Watch out for penguins")
case .East:
    print("Where the sun rises")
case .West:
    print("Where the skies are blue")
}
// 输出 "Watch out for penguins”


相关值


enum Barcode {
    case UPCA(Int,Int,Int)
    case QRCode(String)
}
var productBarcode = Barcode.UPCA(8,85909_51226,3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

switch productBarcode {
case .UPCA(let numberSystem,let identifier,let check):
    print("UPC-A with value of (numberSystem),(identifier),(check).")
case .QRCode(let productCode):
    print("QR code with value of (productCode).")
}
// 输出 "QR code with value of ABCDEFGHIJKLMNOP.”

如果一个枚举成员的所有相关值被提取为常量,或者它们全部被提取为变量,为了简洁,你可以只放置一个var或者let标注在成员名称前:

switch productBarcode {
case let .UPCA(numberSystem,identifier,check):
    print("UPC-A with value of (numberSystem),(check).")
case let .QRCode(productCode):
    print("QR code with value of (productCode).")
}
// 输出 "QR code with value of ABCDEFGHIJKLMNOP."



原始值


enum Planet: Int {
    case Mercury = 1,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune
}

let earthsOrder = Planet.Earth.rawValue
// earthsOrder is 3

枚举类型可以用原始值进行预先填充,上述枚举的原始值类型为int
同时可以通过rawValue访问原始值,可以通过原始值创建枚举

let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.Uranus
let positionToFind = 9
if let somePlanet = Planet(rawValue: positionToFind) {
    switch somePlanet {
    case .Earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
    }
} else {
    print("There isn't a planet at position (positionToFind)")
}
// 输出 "There isn't a planet at position 9

这个范例使用可选绑定(optional binding),通过原始值9试图访问一个行星。
if let somePlanet = Planet(rawValue: 9)语句获得一个可选Planet,如果可选Planet可以被获得,把somePlanet设置成该可选Planet的内容。
在这个范例中,无法检索到位置为9的行星,所以else分支被执行。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读