官术网_书友最值得收藏!

Nested types

Enumerations are often created to support a specific class or structure's functionality. Likewise, it can be convenient to declare utility classes and structures purely to use within the context of a complex type.

Swift enables us to declare nested types, whereby we nest supporting enumerations, classes, and structures within the definition of the type that they support. The following example, borrowed from The Swift Programming Language by Apple Inc., presents nested types:

struct BlackjackCard { 
// nested Suit enumeration
enum Suit: Character {
case spades = "?",
hearts = "?",
diamonds = "?",
clubs = "?"
}

// nested Rank enumeration
enum Rank: Int {
case two = 2, three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace

// nested struct
struct Values {
let first: Int, second: Int?
}

var values: Values {
switch self {
case .ace:
return Values(first: 1, second: 11)
case .jack, .queen, .king:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}

let rank: Rank, suit: Suit

var description: String {
var output = "suit is \(suit.rawValue),"
output += "value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
主站蜘蛛池模板: 隆安县| 神农架林区| 伊川县| 宣威市| 色达县| 镇平县| 木兰县| 德昌县| 翁源县| 三门峡市| 鄂伦春自治旗| 浮山县| 昌乐县| 竹北市| 大冶市| 长沙市| 昌都县| 滦南县| 静海县| 定南县| 赤壁市| 西畴县| 郎溪县| 溆浦县| 张家界市| 醴陵市| 保定市| 玛多县| 同江市| 永年县| 盐源县| 汶上县| 棋牌| 翼城县| 巫溪县| 五河县| 丰镇市| 巨野县| 闵行区| 固阳县| 松潘县|