温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用swift枚举定义

发布时间:2021-10-14 10:08:57 来源:亿速云 阅读:103 作者:iii 栏目:编程语言

本篇内容主要讲解“如何使用swift枚举定义”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用swift枚举定义”吧!

枚举定义

//枚举定义
enum CompassPoint {
    case north
    case south
    case east
    case west
}

//常配合switch case使用
let directionToHead = CompassPoint.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 Planet: CaseIterable {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

for planet in Planet.allCases {
    print(planet)
}
/*
 mercury
 venus
 earth
 mars
 jupiter
 saturn
 uranus
 neptune
 */

关联值

//关联值
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

func showBarcode(_ barcode: Barcode) {
    switch barcode {
    case .upc(let numberSystem, let manufacturer, let product, let check):
        print("UPC:\(numberSystem), \(manufacturer), \(product), \(check)")
    case .qrCode(let productCode):
        print("QR Code: \(productCode)")
    }
}

var productBarcode = Barcode.upc(1, 1, 1, 1)
showBarcode(productBarcode)
//UPC:1, 1, 1, 1
productBarcode = Barcode.qrCode("hello")
showBarcode(productBarcode)
//QR Code: hello

原始值

//原始值
enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

从原始值初始化

//从原始值初始化
enum RoleStatus: Int,CaseIterable {
    case run
    case jump
    case walk
    case idle
}

for i in 0...RoleStatus.allCases.count {
    print(RoleStatus(rawValue: i))
}
/*
 Optional(__lldb_expr_8.RoleStatus.run)
 Optional(__lldb_expr_8.RoleStatus.jump)
 Optional(__lldb_expr_8.RoleStatus.walk)
 Optional(__lldb_expr_8.RoleStatus.idle)
 nil
 */

递归枚举(indirect)

//递归枚举 (5+4)*2
indirect enum ArithmeticExpression {
    case number(Int)
    case addition(ArithmeticExpression, ArithmeticExpression)
    case multiplication(ArithmeticExpression, ArithmeticExpression)
}

let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))

func evaluate(_ expression: ArithmeticExpression) -> Int {
    switch expression {
    case let .number(value):
        return value
    case let .addition(left, right):
        return evaluate(left) + evaluate(right)
    case let .multiplication(left, right):
        return evaluate(left) * evaluate(right)
    }
}

print(evaluate(product))
//18

到此,相信大家对“如何使用swift枚举定义”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI