* 내가 읽으려고 내 맘대로 번역한 글.
* 원문 : https://docs.swift.org/swift-book/LanguageGuide/NestedTypes.html

 

 

 

Nested Types

Enumerations are often created to support a specific class or structure’s functionality. Similarly, it can be convenient to define utility classes and structures purely for use within the context of a more complex type. To accomplish this, Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.

열거형은 종종 특정 클래스나 구조체의 기능을 지원하기 위해서 만들어진다.

마찬가지로, 더 복잡한 타입의 컨텍스트를 사용하기 위해서 유틸리티 클래스나 구조체를 정의하는게 편할수 있다.

이를 위해, swift는 중첩타입을 정의할수 있고,

이것으로 인하여 지원하는 열거형, 클래스, 구조체를 그들이 지원하는 타입의 정의내에서 중첩할수 있다.

 

To nest a type within another type, write its definition within the outer braces of the type it supports. Types can be nested to as many levels as are required.

다른 타입안에 타입을 중첩시키려면, 지원하는 타입의 외부 중괄호 안에 정의를 작성해라.

타입들은 필요한 만큼 많이 중첩될수 있다.

 

Nested Types in Action

The example below defines a structure called BlackjackCard, which models a playing card as used in the game of Blackjack. The BlackjackCard structure contains two nested enumeration types called Suit and Rank.

아래 예제는 블랙잭 게임에서 사용되는 카드게임을 모델링하는 BlackjackCard 라는 구조체를 선언한다.

BlackjackCard 구조체는 Suit 와 Rank 라는 두개의 중첩된 열거형 타입을 포함한다.

 

In Blackjack, the Ace cards have a value of either one or eleven. This feature is represented by a structure called Values, which is nested within the Rank enumeration:

블랙잭에서, Ace 카드는 1 또는 11 의 값을 갖는다.

이 특징은 Values 라는 구조체를 통해서 표현되고, 이것은 Rank 열거형안에 중첩되어 있다.

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
		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 properties and methods
	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
	}
}

 

The Suit enumeration describes the four common playing card suits, together with a raw Character value to represent their symbol.

Suit 열거형은 일반적인 4개의 게임 카드 슈트를 기술하고, raw Character 값과 함께 그들의 심볼을 표현한다.

 

The Rank enumeration describes the thirteen possible playing card ranks, together with a raw Int value to represent their face value. (This raw Int value is not used for the Jack, Queen, King, and Ace cards.)

Rank 열거형은 13개의 게임카드 등수를 기술하고, raw Int 값과 함께 그들의 표면값을 표현한다.

(raw Int 값은 Jack, Queen, King, Ace 카드에는 사용되지 않는다)

 

As mentioned above, the Rank enumeration defines a further nested structure of its own, called Values. This structure encapsulates the fact that most cards have one value, but the Ace card has two values. The Values structure defines two properties to represent this:

위에서 언급했듯이, Rank 열거형은 Values 라는 자체의 중첩된 구조체를 정의한다.

이 구조체는 대부분의 카드가 하나의 값을 가지고 있지만, Ace 카드는 두개의 값을 가지고 있다는 사실을 캡슐화 한다.

Value 구조체는 이것을 표현하기 위하여 두개의 속성을 정의한다.

  • first, of type Int
  • second, of type Int?, or “optional Int
  • Int 타입의 first
  • Int? 또는 옵셔널 Int 타입의 second

 

Rank also defines a computed property, values, which returns an instance of the Values structure. This computed property considers the rank of the card and initializes a new Values instance with appropriate values based on its rank. It uses special values for jack, queen, king, and ace. For the numeric cards, it uses the rank’s raw Int value.

Rank 역시 Values 구조체의 인스턴스를 리턴하는 values 라는 계산 속성을 정의한다.

이 계산 속성은 카드의 순위를 고려하고, 자신의 rank에 기초하여 적절한 값으로 새로운 Values 인스턴스를 초기화한다.

이것은 jack, queen, king, and ace 에는 특별한 값을 사용한다.

숫자카드에는 rank의 raw Int 값을 사용한다.

 

The BlackjackCard structure itself has two properties—rank and suit. It also defines a computed property called description, which uses the values stored in rank and suit to build a description of the name and value of the card. The description property uses optional binding to check whether there is a second value to display, and if so, inserts additional description detail for that second value.

BlackjackCard 구조체 자체는 두개의 속성 -rank 와 suit-을 가진다.

description 이라는 계산 속성도 정의하여, 카드의 이름과 값을 기술하기 위해서 rank 와 suit 에 저장된 값을 사용한다.

description 속성은 옵셔널 바인딩을 사용하여 표시할 두번째 값이 있는지 여부를 검사하고, 있으면,

두번째 값에 대해서 자세한 추가적인 설명을 추가한다.

 

Because BlackjackCard is a structure with no custom initializers, it has an implicit memberwise initializer, as described in Memberwise Initializers for Structure Types. You can use this initializer to initialize a new constant called theAceOfSpades:

BlackjackCard 는 커스텀 초기화를 가지고 있지 않은 구조체기 때문에, 암시적인 memberwise 초기화를 가진다.

이 초기화를 사용하여 theAceOfSpades 라는 상수를 초기화 할수 있다.

let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
print("theAceOfSpades: \(theAceOfSpades.description)")
// Prints "theAceOfSpades: suit is ♠, value is 1 or 11"

 

Even though Rank and Suit are nested within BlackjackCard, their type can be inferred from context, and so the initialization of this instance is able to refer to the enumeration cases by their case names (.ace and .spades) alone. In the example above, the description property correctly reports that the Ace of Spades has a value of 1 or 11.

BlackjackCard 안에 Rank 와 Suit 가 중첩되었더라도, 그 타입은 컨텍스트에서 추정되고,

이 인스턴스의 초기화는 열거형 case 들은 case 이름(.ace .spades) 만으로도 참조할수 있다.

위의 예에서 description 속성은 올바르게 Spades 의 Ace 가 1 또는 11 값을 가지고 있는걸 나타낸다.

 

Referring to Nested Types

To use a nested type outside of its definition context, prefix its name with the name of the type it is nested within:

중첩된 타입이 정의된 컨텍스트 바깥에서 그 중첩된 타입을 사용하려면,

자신이 속한 타입의 이름을 앞에 붙여라.

let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"

 

For the example above, this enables the names of Suit, Rank, and Values to be kept deliberately short, because their names are naturally qualified by the context in which they are defined.

위의 예에서, Suit, Ranj, Values 는 의도적으로 짧게 할수 있다.

왜냐면 그 이름들은 자신이 정의된 컨텍스트에 의해서 자연스럽게 규정되기 때문이다. ???

반응형

'iOS 초보' 카테고리의 다른 글

iOS. UI Test 자동화  (0) 2020.04.17
[swift5.1번역] 20.Extensions  (0) 2019.12.04
[swift5.1번역] 18.Type Casting  (0) 2019.11.25
[swift5.1번역] 17.Error Handling  (0) 2019.11.14
[swift5.1번역] 16.Optional Chaining  (0) 2019.10.11
Posted by 돌비
,