Created
March 30, 2020 09:08
-
-
Save hayabusabusa/21da21b3e7712ee04d207d688e613154 to your computer and use it in GitHub Desktop.
Swift Type Erase test playground.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// MARK: - Entity | |
struct HogeEntity { | |
let title: String | |
} | |
struct FugaEntity { | |
let title: String | |
} | |
// MARK: - Protocol | |
protocol Repository { | |
associatedtype Success | |
func fetch(completion: ((Result<Success, Error>) -> Void)?) | |
} | |
// MARK: - Repositories | |
struct HogeRepository: Repository { | |
typealias Success = HogeEntity | |
func fetch(completion: ((Result<HogeEntity, Error>) -> Void)?) { | |
guard let completion = completion else { return } | |
completion(.success(HogeEntity(title: "Hoge success"))) | |
} | |
} | |
struct FugaRepository: Repository { | |
typealias Success = FugaEntity | |
func fetch(completion: ((Result<FugaEntity, Error>) -> Void)?) { | |
guard let completion = completion else { return } | |
completion(.success(FugaEntity(title: "Fuga success"))) | |
} | |
} | |
// MARK: - Type Erase | |
struct AnyRepository<SuccessType>: Repository { | |
typealias Success = SuccessType | |
private let _fetch: ((((Result<SuccessType, Error>) -> Void)?) -> Void) | |
init<T: Repository>(_ base: T) where T.Success == SuccessType { | |
_fetch = base.fetch | |
} | |
func fetch(completion: ((Result<SuccessType, Error>) -> Void)?) { | |
_fetch(completion) | |
} | |
} | |
// NOTE: これがやりたいけどできない | |
// `associatedType` で与えた型が解決していないためエラーが出る. | |
//let repository: Repository = HogeRepository() | |
let repository: AnyRepository<FugaEntity> = AnyRepository(FugaRepository()) | |
repository.fetch { result in | |
if case .success(let entity) = result { | |
print(entity) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment