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

swift2.0笔记3

发布时间:2020-12-14 07:17:06 所属栏目:百科 来源:网络整理
导读:1. 枚举语法 //1.定义一个枚举类型 //2.必须以大写字母开头 //3.case创建新的枚举值 enum SomeEnumeration { //代码 } enum CompassPoint{ case South case East case North case West} //多个成员值可以出现在同一行上 enum Planet { case Mercury,Venus,Ea

1. 枚举语法

//1.定义一个枚举类型
//2.必须以大写字母开头
//3.case创建新的枚举值
enum SomeEnumeration{
    //代码
}
enum CompassPoint{
    case South
    case East
    case North
    case West
}
//多个成员值可以出现在同一行上
enum Planet {
    case Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune
}
var directionToHead = CompassPoint.West

directionToHead = .North

switch directionToHead {
    case .South:
        print("It is South")
    case .West:
        print("It is west")
    default:
        print("Another direction")
}

2. 枚举关联值

//1.定义一个Barcode枚举类型,一个成员是具有(Int,Int,Int)类型关联值的UPCA,另一个成员是具有String类型关联值的QRCode
//2.枚举类型的常亮和变量只能存储一个枚举值(和其关联值)
enum Barcode{
    case UPCA(Int,Int)
    case QRCode(String)
}

var productBarcode = Barcode.UPCA(8,85909,51226,3)  //枚举类型变量存储一个枚举值和其关联值
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")  //变量存储值被替换,因为只能存储一个枚举值及其关联值

switch productBarcode {
    case .UPCA(let numberSystem,let manufacturer,let product,let check):
        print("UPC-A: (numberSystem),(manufacturer),(product),(check).")
    case .QRCode(let productCode):
        print("QR code: (productCode).")
}

3. 枚举原始值

//1.定义:枚举成员的默认值称为原始值
//2.原始值的类型必须相同
//3.原始值在枚举值中声明必须唯一

enum ControlChar: Character{
    case Tab = "t"
    case LineFeed = "n"
    case CarriageReturn = "r"
}
//关联值和原始值的区别
//1.原始值在定义枚举值被预先填充的值,原始值是不变的
//2.关联值是枚举类型的一个变量,这个变量是基于枚举成员的值,关联值是可以变化的

enum PlanetAgain: Int {
    case Mercury = 1,Neptune
}
let earthsOrder = PlanetAgain.Earth.rawValue
print(earthsOrder)

//在上面的例子中,Plant.Mercury 的显式原始值为 1.Planet.Venus 的隐式原始值为 2.依次类推。

enum CompassPointAgain: String {
    case North,South,East,West
}
let sunsetDirection = CompassPointAgain.West.rawValue
print(sunsetDirection)
//上面例子中,CompassPoint.South 拥有隐式原始值 South,依次类推。

4. 使用原始值初始化枚举实例

//1.原始值构造器返回一个可选的枚举成员
//2.下例中的possiblePnalet是可选的
let possiblePnalet = PlanetAgain(rawValue: 7)

print(possiblePnalet!)

(编辑:李大同)

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

    推荐文章
      热点阅读