2. NHN NEXT Eunjoo Im
Type
casting
소개
▪ Type casting은 객체 인스턴스의 타입을 확인하거나 고유
위계질서의 슈퍼클래스나 서브클래스로 취급하는 방법
▪ is와 as 오퍼레이터를 사용하며, 쉽게 특정 값의 타입을 확
인하거나 다른 타입으로 캐스팅 가능
▪ 타입이 프로토콜을 따르는지 확인할 수 있음
▪ is: 인스턴스가 프로토콜을 따르면 true, 따르지 않으
면 false
▪ as?: 다운캐스팅 오퍼레이터로 프로토콜 타입의 옵셔
널 값을 반환하며, 프로토콜을 따르지 않으면 nil
▪ as!: 프로토콜 타입을 강제로 다운캐스트하며 성공하
지 않으면 런타임 에러
출처: Apple Inc. The Swift Programming Language (Swift 3)
3. NHN NEXT Eunjoo Im
Type
casting으로
프로토콜 확인
출처: Apple Inc. The Swift Programming Language (Swift 3)
protocol HasArea {
var area: Double { get }
}
class Circle: HasArea {
let pi = 3.1415927
var radius: Double
var area: Double { return pi * radius * radius
}
init(radius: Double) { self.radius = radius }
}
class Animal {
var legs: Int
init(legs: Int) { self.legs = legs }
}
let objects: [AnyObject] = [
Circle(radius: 2.0),
Animal(legs: 4)
]
for object in objects {
if let objectWithArea = object as? HasArea {
print("Area is (objectWithArea.area)")
else print(“no area")
}
// Area is 12.5663708
// Something that doesn't have an area
어떤 값이 찍힐까요?
4. NHN NEXT Eunjoo Im
Type
casting으로
프로토콜 확인
출처: Apple Inc. The Swift Programming Language (Swift 3)
protocol HasArea {
var area: Double { get }
}
class Circle: HasArea {
let pi = 3.1415927
var radius: Double
var area: Double { return pi * radius * radius
}
init(radius: Double) { self.radius = radius }
}
class Animal {
var legs: Int
init(legs: Int) { self.legs = legs }
}
let objects: [AnyObject] = [
Circle(radius: 2.0),
Animal(legs: 4)
]
for object in objects {
if let objectWithArea = object as? HasArea {
print("Area is (objectWithArea.area)")
else print(“no area")
}
// Area is 12.5663708
// no area
5. NHN NEXT Eunjoo Im
Type
casting
위계질서
출처: Apple Inc. The Swift Programming Language (Swift 3)
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "Casablanca", director:
"Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist:
"Elvis Presley")
] // the type of "library" = [MediaItem]
6. NHN NEXT Eunjoo Im
Type Check
(is)
▪ is: 인스턴스가 서브클래스면 true, 아니면 false 반환
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains (movieCount) movies and
(songCount) songs”)
// Prints "Media library contains 2 movies and 3 songs
출처: Apple Inc. The Swift Programming Language (Swift 3)
7. NHN NEXT Eunjoo Im
Down
casting
(as?), (as!)
▪ as?: 인스턴스를 서브클래스로 다운캐스팅하며, 옵셔널 서
브클래스를 반환, 실패하면 값은 nil
▪ as!: 인스턴스를 서브클래스로 강제로 다운캐스팅, 실패시
런타임 에러
▪ 실제 인스턴스가 변화하지는 않으며 해당 클래스로 취급함
for item in library {
if let movie = item as? Movie {
print("Movie: (movie.name), dir. (movie.director)")
} else if let song = item as? Song {
print("Song: (song.name), by (song.artist)")
}
}
// Movie: Casablanca, dir. Michael Curtiz
// Song: Blue Suede Shoes, by Elvis Presley
출처: Apple Inc. The Swift Programming Language (Swift 3)
8. NHN NEXT Eunjoo Im
Any
AnyObject
(1)
▪ Any: 모든 타입의 인스턴스를 받을 수 있음(function 포
함)
▪ AnyObject: 모든 타입의 클래스 타입을 받을 수 있음
▪ switch문에 is나 as 패턴을 써서 타입을 매칭할 수 있음
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan
Reitman"))
things.append({ (name: String) -> String in "Hello, (name)" })
let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
출처: Apple Inc. The Swift Programming Language (Swift 3)
Any 자리에 옵셔널을
쓰면 warning이 뜨니
as 로 명시적으로 쓸 것
9. NHN NEXT Eunjoo Im
Any
AnyObject
(2)
case is Double:
print("some other double value that I
don't want to print")
case let someString as String:
print("a string value of "(someString)
"")
case let (x, y) as (Double, Double):
print("an (x, y) point at (x), (y)")
case let movie as Movie:
print("a movie called (movie.name), dir.
(movie.director)")
case let stringConverter as (String) ->
String:
print(stringConverter("Michael"))
default:
print("something else")
}
출처: Apple Inc. The Swift Programming Language (Swift 3)
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of (someInt)")
case let someDouble as Double where
someDouble > 0:
print("a positive double value of
(someDouble)")
10. NHN NEXT Eunjoo Im
Any
AnyObject
(3)
// zero as an Int
// zero as a Double
// an integer value of 42
// a positive double value of 3.14159
// a string value of "hello"
// an (x, y) point at 3.0, 5.0
// a movie called Ghostbusters, dir. Ivan Reitman
// Hello, Michael
출처: Apple Inc. The Swift Programming Language (Swift 3)
11. NHN NEXT Eunjoo Im
Nested
Type (1)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ enumeration, 클래스, 구조체의 중첩을 가능하게 해서 복
잡한 타입을 구현할 수 있게 함
▪ struct 안에 enum을 포함할 수 있고, 그 enum 안에 또
struct를 넣을 수 있음
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)
}
}
12. NHN NEXT Eunjoo Im
Nested
Type (2)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ Suits enum는 4종류의 card suit와 심볼을 나타내는
Character 값을 가짐
▪ Rank enum은 13개의 카드 랭크와 Int 값을 가짐
// 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
}
}
13. NHN NEXT Eunjoo Im
Nested
Type (3)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ Values 구조체의 프로퍼티
▪ Int 타입의 first
▪ Int?타입의 second
▪ Rank의 computed 프로퍼티 values는 Values 구조체의
인스턴스를 반환
▪ values는 카드의 rank에 따라 새 Values 인스턴스를 rank
에 맞는 값으로 초기화함
▪ 잭/퀸/킹/에이스에는 특별값 사용, 숫자에는 Int값 사용
▪ BlackjackCard 초기화의 프로퍼티
▪ rank
▪ suit
▪ description(computed property): rank와 suit 값
을 사용하며, optional binding을 사용해서 second
값이 있으면 추가 설명을 만듦
14. NHN NEXT Eunjoo Im
Nested
Type (4)
출처: Apple Inc. The Swift Programming Language (Swift 3)
▪ BlackjackCard는 암시적 초기화 사용
▪ 문맥으로부터 중첩 프로퍼티의 타입 추정
let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades)
print("theAceOfSpades: (theAceOfSpades.description)")
// Prints "theAceOfSpades: suit is ♠, value is 1 or 11"
let heartsSymbol = BlackjackCard.Suit.hearts.rawValue
// heartsSymbol is "♡"
▪ 중첩 프로퍼티에 중첩 표현으로 접근할 수 있음