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

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
}
}
主站蜘蛛池模板: 惠安县| 广昌县| 全南县| 四平市| 库伦旗| 丹阳市| 宝应县| 萨迦县| 灵川县| 阜南县| 邯郸县| 崇仁县| 定结县| 仁怀市| 惠东县| 时尚| 东方市| 班玛县| 天全县| 徐水县| 夏邑县| 铜川市| 蚌埠市| 会东县| 富川| 泰顺县| 嘉鱼县| 中山市| 松原市| 上栗县| 依安县| 丹阳市| 扎赉特旗| 宁南县| 江山市| 若尔盖县| 上饶县| 天镇县| 香港| 惠水县| 松滋市|