# nested types

[Swift](https://lochiwei.gitbook.io/ios/swift) ⟩ [type](https://lochiwei.gitbook.io/ios/swift/type) ⟩ [category](https://lochiwei.gitbook.io/ios/swift/type/category) ⟩ nested types

{% tabs %}
{% tab title="🔴 主題" %}

* [extension-of-nested-type](https://lochiwei.gitbook.io/ios/swift/type/category/nested-types/extension-of-nested-type "mention")
* [to-nest-or-not-to-nest](https://lochiwei.gitbook.io/ios/swift/type/category/nested-types/to-nest-or-not-to-nest "mention")
  {% endtab %}

{% tab title="📗 參考" %}

* [x] AppCoda ⟩ [Nested Objects in Swift](https://www.appcoda.com.tw/swift-nested-object/) (善用 Swift 的嵌套物件功能)
  {% endtab %}

{% tab title="👁️ 預覽" %}

```swift
struct Blackjack {

    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
    }
}

// extension can have nested types
extension Blackjack {

    // ⭐️ nested type: `Blackjack.Suit`
    enum Suit: Character {
        case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣"
    }

    // ⭐️ nested type: `Blackjack.Rank`
    enum Rank: Int {
    
        case two = 2, three, four, five, six, seven, eight, nine, ten
        case jack, queen, king, ace
        
        // ⭐️ nested type: `Blackjack.Rank.Values`
        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)
            }
        }
    }
}
```

{% endtab %}

{% tab title="💈範例" %}
\*
{% endtab %}

{% tab title="📘 手冊" %}

* Swift ⟩ [Nested Types](https://docs.swift.org/swift-book/LanguageGuide/NestedTypes.html)
  {% endtab %}

{% tab title="👥 相關" %}

* [ext](https://lochiwei.gitbook.io/ios/swift/type/ext "mention") can define nested types.
* can have [extension-of-nested-type](https://lochiwei.gitbook.io/ios/swift/type/category/nested-types/extension-of-nested-type "mention").
  {% endtab %}
  {% endtabs %}
