[swift] A Swift Tour -Enumerations and Structures
📌 Apple의 공식 문서인 The Swift Programming Language (Swift 5.5)에서 A Swift Tour를 말 그대로 '재빨리 둘러보며' 정리한 포스트입니다.
📙Enumerations and Structures
📖Enumeration
📎Enum
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
- method 가질 수 있음
- 원시값은 0에서 시작해 1씩 증가(명시적으로 값 지정해서 변경 가능)
rawValue
속성을 통해 원시값에 접근
📎init?(rawValue:)
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
print(threeDescription) //3
}
- 원시값으로 열거체의 instance 생성
- 원시값과 일치하는 case의 원시값을 반환, 일치하는 Rank가 없는 경우
nil
을 반환
📎The case values of an enumeration
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
- 각 case는 그 자체로 고유의 값
→ 원시값이 의미가 없는 경우, 원시값을 제공하지 않아도 됨
- 값의 type을 안다면
switch
문에서처럼 축약형으로 사용 가능
📎Associated values
원시값 : case의 모든 instance가 같은 값 가짐
→ 연관값으로 극복
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out if cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
} //Sunrise is at 6:00 am and sunset is at 8:09 pm.
📖Structure
➰class와 유사
➰가장 큰 차이점: class → call by reference, struct → call by value
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
Author And Source
이 문제에 관하여([swift] A Swift Tour -Enumerations and Structures), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://velog.io/@imeyh/swift-A-Swift-Tour-Enumerations-and-Structures
저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
rawValue
속성을 통해 원시값에 접근if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
print(threeDescription) //3
}
nil
을 반환enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
→ 원시값이 의미가 없는 경우, 원시값을 제공하지 않아도 됨
switch
문에서처럼 축약형으로 사용 가능원시값 : case의 모든 instance가 같은 값 가짐
→ 연관값으로 극복
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out if cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
} //Sunrise is at 6:00 am and sunset is at 8:09 pm.
➰class와 유사
➰가장 큰 차이점: class → call by reference, struct → call by value
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
Author And Source
이 문제에 관하여([swift] A Swift Tour -Enumerations and Structures), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@imeyh/swift-A-Swift-Tour-Enumerations-and-Structures저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)