본문 바로가기

Swift/Foundation

Bridging

Swift에서 구현한 기본 타입들(Int, String)을 NS로 변형하는 과정을 bridging이라고 표현한다.

as를 사용해서 타입이 Error를 NSError로 변환 가능한지 궁금했다.

catch let error as NSError

 

 

In the meanwhile, developers who must handle an Objective-C exception can always do so by writing a stub in Objective-C to explicitly "bridge" the exception into an NSError out parameter. This isn't ideal, but it's acceptable.

구현할 때 Error < - > NSError로 bridging이 가능하도록 구현했다. 

(Error는 프로토콜이고 NSError는 Class이다.)

 

 


 

기본 클래스에서 bridging하는 방법

 

bridging에 대해서 자료를 찾던 중 발견한 블로그 글에서 힌트를 얻고 직접 구현했다.

NSCustomType을 생성하고 typealias로 Name의 타입을 CustomStruct로 선언해준다. 

 

 

 

CustomType을 생성하고 typealias로 Name 타입을 NSCustomType.Name으로 선언해준다.

이렇게 구현하면 외부에서 봤을 때는 CustomType의 name 속성은 CustomType.Name이지만,

내부적으론 NSCustomType.Name을 사용하고 있다.

 

 

 

결국 bridging이라고 표현한 방법은 외부에서 봤을 때는 다른 타입이지만,

내부에서 typealias를 사용해서 같은 타입을 사용하고 있어서 as로 변환이 가능하게 구현하는 것이다.

(실패할 가능성이 없는 이유 같은 타입이기 때문에)

 

 

 

Reference

https://corykim0829.github.io/ios/NS-classes-in-Swift/#

'Swift > Foundation' 카테고리의 다른 글

Properties  (0) 2020.08.06
Dispatch Queue  (0) 2020.08.04
class, struct  (0) 2020.08.03
Out of Bounds  (0) 2020.06.28
MVC Design Pattern  (0) 2020.06.28