Skip to content

Instantly share code, notes, and snippets.

@hayabusabusa
Created March 30, 2020 09:08
Show Gist options
  • Save hayabusabusa/21da21b3e7712ee04d207d688e613154 to your computer and use it in GitHub Desktop.
Save hayabusabusa/21da21b3e7712ee04d207d688e613154 to your computer and use it in GitHub Desktop.
Swift Type Erase test playground.
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