ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (Swift) Generic 제네릭
    iOS💖 2024. 10. 11. 19:31

    Swift의 대부분의 표준 라이브러리*는 Generic 으로 선언되어 있다고 한다.

     

    Generic 이란?

    타입에 제한 받지 않고 범용 코드를 작성할 때 사용된다.

     

     

    Generic 표시

    enum, structure, func의 이름 옆 에 <T> 를 표시하여, Generic 임을 표시한다.

    enum ParseResult<T> {
    	...
    }
    
    func load<T>(_ resource: Resource<T>) -> AnyPublisher<T, Error> {
    	...
    }
    
    struct Resource<T: Decodable> {
    	...
    }

     

     

    Generic 사용 예시

    @Published private(set) var user: UserProfile?
    
    let network = NetworkService(configuration: .default)
    
    let resource = Resource<UserProfile>(   // UserProfile은 network에서 받아온 데이터 모델, Resource<T>는 network url request를 위한 리소스
        base: "https://api.github.com/",
        path: "users/\(keyword)",
        params: [:],
        header: ["Content-Type": "application/json"])
        
    network.load(resource)
        .receive(on: Runloop.main)
        .sink(receiveCompletion: { completion in 
            print("[Completion] \(completion)")
            switch completion {
            case .failure(let error):
                self.user = nil
                print("[Error] \(error)")
            case .finished: break
            }
        }, receiveValue: { user in
            self.user = user
        }).store(in: &subscriptions)

     

     

    Subscripbers.Completion<Failure>

    subscribers의 Completion<Failure> 은 enum이다. 

    case finished  -> 성공,

             failure(Failure에 대한 매개변수) -> 실패

    두가지 case를 가졌다.. 

    Subscribers > Completion<Failure>

     

     

     

     

     

     

    * 표준 라이브러리 :

    Fundamental data types - Int, Double, String,

    Common data structures - Array, Dictionary, Set,

    Global functions - print(_:separator:terminator:), abs(_:),

    Protocols - Collection, Equatable,

    etc.

     

     

    https://developer.apple.com/documentation/swift/swift-standard-library/

     

    Swift Standard Library | Apple Developer Documentation

    Solve complex problems and write high-performance, readable code.

    developer.apple.com

     

    'iOS💖' 카테고리의 다른 글

    (Swift) @frozen  (3) 2024.10.14
    (Swift) private(set) var  (0) 2024.10.11
    (Swift) mutating  (1) 2024.10.11
    (Combine) Scheduler, Operator  (3) 2024.10.07
    (Combine) Publisher, Subscriber + Subject  (4) 2024.10.01

    댓글

Designed by black7375.