- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 212字
- 2021-07-02 23:54:29
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
}
}
推薦閱讀
- 數(shù)據(jù)存儲架構(gòu)與技術(shù)
- Hands-On Data Structures and Algorithms with Rust
- 數(shù)據(jù)產(chǎn)品經(jīng)理高效學習手冊:產(chǎn)品設(shè)計、技術(shù)常識與機器學習
- Greenplum:從大數(shù)據(jù)戰(zhàn)略到實現(xiàn)
- Modern Programming: Object Oriented Programming and Best Practices
- Python數(shù)據(jù)分析、挖掘與可視化從入門到精通
- 大數(shù)據(jù)導論
- 數(shù)據(jù)驅(qū)動:從方法到實踐
- Spark大數(shù)據(jù)編程實用教程
- 網(wǎng)站數(shù)據(jù)庫技術(shù)
- 基于OPAC日志的高校圖書館用戶信息需求與檢索行為研究
- 大數(shù)據(jù)架構(gòu)商業(yè)之路:從業(yè)務需求到技術(shù)方案
- SQL應用及誤區(qū)分析
- 大數(shù)據(jù)數(shù)學基礎(chǔ)(Python語言描述)
- SIEMENS數(shù)控技術(shù)應用工程師:SINUMERIK 840D-810D數(shù)控系統(tǒng)功能應用與維修調(diào)整教程