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

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
}
}
主站蜘蛛池模板: 呼和浩特市| 兴安县| 荆门市| 长寿区| 固阳县| 望城县| 金昌市| 金昌市| 昌都县| 南雄市| 绥阳县| 绥阳县| 桃源县| 仁化县| 定南县| 灵璧县| 海门市| 朝阳区| 邵东县| 和林格尔县| 永济市| 灵寿县| 敦煌市| 申扎县| SHOW| 弥渡县| 确山县| 阿巴嘎旗| 赤水市| 禄劝| 绥江县| 南京市| 全州县| 米脂县| 永康市| 名山县| 镇赉县| 蒙山县| 伊宁市| 柞水县| 鄂尔多斯市|