Created
October 13, 2018 03:00
-
-
Save freddi-kit/47746f60259c16e134413d6aa15b6ecc to your computer and use it in GitHub Desktop.
This file contains 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 UIKit | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
protocol APIClient { | |
associatedtype GetDataType | |
func get() | |
} | |
protocol APIClientDelegate: class { | |
associatedtype GetDataType | |
func getDataIsFinished(data: GetDataType) | |
} | |
class AnyAPIClientDelegate<GetType>: APIClientDelegate { | |
private let _getDataIsFinished: ((GetType) -> Void) | |
required init<U: APIClientDelegate>(_ delegate: U) where U.GetDataType == GetType { | |
self._getDataIsFinished = delegate.getDataIsFinished | |
} | |
func getDataIsFinished(data: GetType) { | |
_getDataIsFinished(data) | |
} | |
} | |
class GetGoogleDataClient: APIClient { | |
typealias GetDataType = String | |
var delegate: AnyAPIClientDelegate<GetDataType>? | |
private var dataTask: URLSessionDataTask? | |
private let urlString: String = "https://google.com/" | |
func get() { | |
let dataTask = URLSession.shared.dataTask(with: URL(string: urlString)!) { [weak self] data, error, response in | |
if let data = data, let stringData = String(data: data, encoding: .utf8) { | |
self?.delegate?.getDataIsFinished(data: stringData) | |
} | |
} | |
dataTask.resume() | |
} | |
} | |
class Hoge { | |
let dataClient = GetGoogleDataClient() | |
init() { | |
dataClient.delegate = .init(self) | |
} | |
func showSomeData() { | |
dataClient.get() | |
} | |
} | |
extension Hoge: APIClientDelegate { | |
func getDataIsFinished(data: String) { | |
print(data) | |
} | |
} | |
let hoge = Hoge() | |
hoge.showSomeData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment