swift4学习笔记(三)

枚举

使用enum关键字定义
case关键字明确了要定义的枚举成员值(相当于定义变量时使用的var关键字,定义枚举成员值则使用关键字case)。
多个成员值可以在同一行,用逗号隔开。

enum Rank:Int{
    case acr = 1
    case two,three,four,five,six,seven,eight,nine,ten
    case jack,queen,king
}
使用switch来匹配枚举
let rank = Rank.ace

func simpleDescription () -> String {
    switch rank {
    case .ace:
        return "ace"
    case .two:
        return "two"
    case .jack:
        return "jack"
    case .queen:
        return "queen"
    default:
        return ""
    }
    
}
可以在枚举中添加方法
enum Suit {
    case spades, hearts, diamonds, clubs
    func simpleDescription() -> String {
        switch self {
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
关联值
enum ServerResponse {
    case result(String, String)
    case failure(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")

结构体

用struct来创建一个结构体,结构体支持和类一样的许多行为包括方法和初始化。结构体和类最重要的一个却别是:结构体在代码中传递是通过复制,而类的传递是通过引用。

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

猜你喜欢

转载自blog.csdn.net/weixin_42779997/article/details/88115682