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

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
}
}
主站蜘蛛池模板: 茌平县| 安陆市| 浦江县| 老河口市| 当雄县| 仪陇县| 阜宁县| 上虞市| 巴南区| 广南县| 长岛县| 会同县| 葵青区| 岳池县| 济源市| 南皮县| 新营市| 米林县| 泾阳县| 健康| 原阳县| 新昌县| 六枝特区| 阜平县| 六安市| 青神县| 沙洋县| 临沂市| 蒙自县| 德钦县| 麦盖提县| 新干县| 宝丰县| 都江堰市| 贵南县| 页游| 毕节市| 金寨县| 麻阳| 和田县| 腾冲县|