한 줄 뜻
같은 호출이 실제로 들어 있는 형식에 따라 다르게 움직이는 것이에요. Swift 에서는 class 상속뿐 아니라 protocol 을 따르는 struct 끼리도 이렇게 사용해요.
왜 필요한가
지도에 핀을 찍는 코드가 if 카페면 ... else if 역이면 ... 으로 짜여 있으면, 박물관을 더할 때마다 이 줄을 찾아 고쳐야 해요. 비슷한 if 사슬이 화면마다 생기면 하나쯤은 빠뜨려요.
장소마다 pin() 을 갖게 하고 지도 코드는 place.pin() 만 부르면, 새 장소는 자기 pin() 만 가지고 오면 돼요. 형식을 나눠야 하는 곳은 switch 한 곳에 모아요.
일상 비유
리모컨의 전원 단추를 떠올려 보세요. TV 를 향하면 TV 가, 에어컨을 향하면 에어컨이 켜져요. 단추는 하나인데 받는 기기가 알아서 자기 방식으로 켜져요. 단추가 기기 종류마다 따로 있다면 리모컨이 금방 단추투성이가 될 거예요.
예제 코드
main.swift · 66줄let places: [any Place] = [ Cafe(name: "Bean Lab", seats: 18), Station(name: "City Hall", lines: [1, 2]), Park(name: "Riverside", dogsAllowed: true),]for place in places { print(place.pin())} var cafes = 0for place in places { if place is Cafe { cafes += 1 } if let station = place as? Station { print("\(station.name) has \(station.lines.count) lines") }}print("cafes: \(cafes)")let note = describe(places[2])print(note) protocol Place { var name: String { get } func pin() -> String} struct Cafe: Place { let name: String let seats: Int func pin() -> String { "[cafe] \(name)" }} struct Station: Place { let name: String let lines: [Int] func pin() -> String { "[train] \(name)" }} struct Park: Place { let name: String let dogsAllowed: Bool func pin() -> String { "[park] \(name)" }} func describe(_ place: any Place) -> String { switch place { case let cafe as Cafe where cafe.seats > 10: return "\(cafe.name): roomy cafe" case is Cafe: return "small cafe" case let park as Park: return park.dogsAllowed ? "\(park.name): dogs welcome" : "\(park.name): no dogs" default: return "\(place.name): just a place" }}
Swift 코드는 이 화면에서 실행하지 않아요. 고친 코드는 내 컴퓨터에서 main.swift 로 저장하고 swiftc 로 컴파일해 돌려 보세요.
언제 사용하나
- 여러 형식을 한 배열이나 한 매개변수로 받아 같은 일을 시킬 때(
[any Place]) - 특정 형식일 때만 하는 일이 있을 때는
as? 로 꺼내 if let - 형식에 따라 갈래가 여럿이면
switch 와 case let x as T, 조건은 where
any Place 는 "어떤 형식인지는 실행할 때 정해지는 상자"라는 표시예요(Swift 5.6 부터 이렇게 적어요). 형식이 하나로 정해져 있으면 some Place 로 적을 수도 있어요.
switch 에서 case let cafe as Cafe where cafe.seats > 10 처럼 형식과 조건을 한 줄에 같이 걸어요.
자주 하는 실수
protocol 형식으로 담고 그 형식만의 칸을 읽음
any Place 로 담으면 protocol 에 적힌 name 과 pin() 만 보여요. 카페에만 있는 seats 는 as? Cafe 로 꺼낸 다음에 읽어요. 이런 일이 잦으면 그 값을 protocol 에 올릴지 생각해 봐요.
틀린 코드
let first: any Place = Cafe(name: "Nook", seats: 6)print(first.seats)
Swift 컴파일러가 내는 오류error: value of type 'any Place' has no member 'seats'
고친 코드
let first: any Place = Cafe(name: "Nook", seats: 6)if let cafe = first as? Cafe { print(cafe.seats)}
실행하면6
switch 에 나머지 갈래가 없음
Swift 의 switch 는 모든 경우를 다 다뤄야 해요. Place 를 따르는 형식은 나중에 얼마든지 늘 수 있으니 default 가 있어야 해요. enum 이라면 case 를 모두 적어도 돼요.
틀린 코드
let spot: any Place = Park(name: "Hill", dogsAllowed: false)switch spot {case is Cafe: print("cafe")case is Park: print("park")}
Swift 컴파일러가 내는 오류error: switch must be exhaustive
고친 코드
let spot: any Place = Park(name: "Hill", dogsAllowed: false)switch spot {case is Cafe: print("cafe")case is Park: print("park")default: print("other place")}
실행하면park
as 로 형식을 내리려 함
as 는 실패할 일이 없는 바꾸기에만 사용해요. protocol 형식을 구체 형식으로 내리는 건 틀릴 수 있으니 as?(실패하면 nil)를 사용해요. as! 도 있지만 틀리면 실행하다 멈춰요.
틀린 코드
let stop: any Place = Station(name: "Port", lines: [4])let station = stop as Stationprint(station.lines)
Swift 컴파일러가 내는 오류error: 'any Place' is not convertible to 'Station'
고친 코드
let stop: any Place = Station(name: "Port", lines: [4])if let station = stop as? Station { print(station.lines)}
실행하면[4]
확인 문제
문제 1
반려견을 받지 않는 공원을 describe 에 넘겼어요. 무엇이 찍힐까요?
let spot: any Place = Park(name: "Hill", dogsAllowed: false)print(describe(spot))
답과 까닭 보기
답: 3. Hill: no dogs case let park as Park 에 걸리고, 안의 삼항 연산자가 dogsAllowed 가 false 인 쪽 글을 골라요.
문제 2
자리가 4개인 카페예요. describe 는 무엇을 돌려줄까요?
let spot: any Place = Cafe(name: "Dot", seats: 4)print(describe(spot))
답과 까닭 보기
답: 2. small cafe 첫 갈래는 where cafe.seats > 10 조건이 거짓이라 건너뛰고, 다음 case is Cafe 에 걸려요. 갈래는 위에서부터 차례로 맞춰 봐요.
자주 묻는 것
any Place 는 무엇인가요?
Place protocol 을 따르는 어떤 형식이든 담는 상자라는 뜻이에요. 실제 형식은 실행할 때 정해지고, 상자로는 protocol 에 적힌 것만 보여요. Swift 5.6 부터 any 를 앞에 적어요.
is 와 as? 는 무엇이 다른가요?
is 는 그 형식인지 참·거짓만 알려 줘요. as? 는 그 형식이면 바꾼 값을, 아니면 nil 을 줘서 if let 과 같이 사용해요. as! 는 틀리면 실행하다 멈춰서 되도록 피해요.
switch 에 default 가 왜 필요한가요?
Swift 의 switch 는 모든 경우를 다뤄야 해요. protocol 을 따르는 형식은 나중에 늘 수 있으니 default 가 있어야 컴파일돼요. enum 이면 case 를 모두 적어도 돼요.