iOS

(Swift) Result 타입에 대한 값 맵핑 하기

2023. 9. 27. 16:17
목차
  1. Network 통신을 통해 Response로 받아올 Result 타입을 원하는 형태로 맵핑하기

Network 통신을 통해 Response로 받아올 Result 타입을 원하는 형태로 맵핑하기

 

🔥 목표: 네트워크 통신의 결과로 completion Handler에 내보내줄 Result<T: Decodable, Error>  타입의 값을 원하는 타입으로 맵핑하기

func map<NewSuccess>(
    _ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure>

func mapError<NewFailure>(
    _ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> where NewFailure : Error

map<NewSuccess>: Result의 성공시 반환 타입을 새로운 타입으로 맵핑하는 메서드
mapError<NewFailure>: Result의 실패시 반환 타입을 새로운 타입으로 맵핑하는 메서드

 

 

- Response 모델 타입

struct SubwayStationResponseDTO: DTOMapping {

    private let searchInfo: SearchInfoBySubwayNameServiceModel
    var stations: [SubwayStationDTO] { searchInfo.row }

    enum CodingKeys: String, CodingKey {
        case searchInfo = "SearchInfoBySubwayNameService"
    }

    func toDomain() -> [SubwayStation] {
        return stations.map { $0.toDomain() }
    }

}

 

- 네트워크 통신 로직

extension NetworkManager {

    func request<T: Decodable>(
        type: T.Type,
        api: Router,
        completion: @escaping (Result<T, NetworkError>) -> Void
    ) {

        AF.request(api)
        .responseDecodable(of: T.self) { response in
            print(response.request?.url)

            switch response.result {
            case .success(let data):
                completion(.success(data))
            case .failure:
                let networkError = NetworkError(rawValue: response.response?.statusCode ?? 0)
                completion(.failure(networkError ?? .unknownError))
            }
        }
    }

}

 

- 레포지토리에서 네트워크 통신 로직 호출시, Result 타입의 값을 다른 타입으로 맵핑하기

extension DefaultFetchStationRepository: FetchStationRepository {

    func fetchStationByName(
        name: String,
        completion: @escaping (Result<[SubwayStation], NetworkError>) -> Void
    ) {
        networkManager.request(
            type: SubwayStationResponseDTO.self,
            api: .subwayStationInfo(query: name)
        ) { result in
            let mappedResult = result.map { $0.toDomain() }
            completion(mappedResult)
        }
    }

}

Result의 기존 Success 타입(DTO)을 새로운 NewSuccess 타입(Domain Entitiy)으로 맵핑!

이제 UseCase에서 해당 레포지토리 메서드를 통해 원하는 로직을 바로 구현하면 된다.

레포지토리에서 Data Layer의 DTO타입을 Domain Layer의 Entity 타입으로 맵핑하고, UseCase로 넘기는 흐름으로 구현했다.

 

 

https://developer.apple.com/documentation/swift/result/map(_:)

 

map(_:) | Apple Developer Documentation

Returns a new result, mapping any success value using the given transformation.

developer.apple.com

https://developer.apple.com/documentation/swift/result/maperror(_:) 

 

mapError(_:) | Apple Developer Documentation

Returns a new result, mapping any failure value using the given transformation.

developer.apple.com

 

'iOS' 카테고리의 다른 글

TextField의 복사/붙여넣기 기능 막기(feat. canPerformAction)  (0) 2023.08.10
  1. Network 통신을 통해 Response로 받아올 Result 타입을 원하는 형태로 맵핑하기
'iOS' 카테고리의 다른 글
  • TextField의 복사/붙여넣기 기능 막기(feat. canPerformAction)
예스코치
예스코치
정리를 위한 공부
YescoachiOS정리를 위한 공부
예스코치
YescoachiOS
예스코치
전체
오늘
어제
  • 분류 전체보기 (18)
    • SeSAC (11)
    • iOS (2)
    • 알고리즘∙코테 (1)
    • TIL (0)
    • 트러블슈팅 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • endEditing
  • IBInspectable
  • 새싹
  • SearchBar
  • UIPageControl
  • canPerformAction
  • RefreshControl
  • SESAC
  • Result Mapping
  • til
  • UserNotification
  • CHCR
  • IBDesignable
  • 새싹 iOS
  • Code-base UI
  • isSecureTextEntry
  • layoutSubviews
  • ios
  • ActivityIndicator
  • required init
  • Swift
  • iOS 앱 개발자 데뷔 과정 PLUS
  • UIResponderStandardEditActions
  • 영등포 5기
  • dynamic color
  • lazy stored property
  • textContentType
  • UITextField
  • UITraitCollection
  • resignFirstResponder

최근 댓글

최근 글

hELLO · Designed By 정상우.
예스코치
(Swift) Result 타입에 대한 값 맵핑 하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.