对照Java学习Swift--嵌套类型(Nested Types)

时间:2022-08-07 15:40:19

这个很简单,就是在类型的内部定义一个类型,跟Java中的内部类很相似,Swift 允许你定义嵌套类型,可以在支持的类型中定义嵌套的枚举、类和结构体。

嵌套类型实践

看个例子,也是apple的官网上拿过来的:

struct BlackjackCard {
// 嵌套的 Suit 枚举
enum Suit: Character {
case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
}

// 嵌套的 Rank 枚举
enum Rank: Int {
case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King, Ace
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)
}
}
}

// BlackjackCard 的属性和方法
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
}
}

看下怎样定义BlackjackCard的实例:

let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
print("theAceOfSpades: \(theAceOfSpades.description)")

尽管Rank和Suit嵌套在BlackjackCard中,但它们的类型仍可从上下文中推断出来,所以在初始化实例时能够单独通过成员名称(.Ace和.Spades)引用枚举实例。

引用嵌套类型

在外部引用嵌套类型时,在嵌套类型的类型名前加上其外部类型的类型名作为前缀:

let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue

这一节很简单。