Skip to content

Instantly share code, notes, and snippets.

@hamsternik
Created March 19, 2017 23:14
Show Gist options
  • Save hamsternik/fc457b134193b7d5754e72e79b7b51eb to your computer and use it in GitHub Desktop.
Save hamsternik/fc457b134193b7d5754e72e79b7b51eb to your computer and use it in GitHub Desktop.
Transform UIModel object to the Model using protocols
import Foundation
// MARK: Model
protocol ModelType {
init(value: Int)
}
class Model: ModelType {
var value: Int
required init(value: Int) {
self.value = value
}
}
// MARK: View Model
protocol UIModelType {
associatedtype CType
func model() -> CType
}
class UIModel: UIModelType {
var strValue: String
init(strValue: String) {
self.strValue = strValue
}
func model() -> Model {
return Model(value: (strValue as NSString).integerValue)
}
}
extension Array where Element: UIModelType {
func models() -> [Element.CType] {
return self.map{ $0.model() }
}
}
// MARK: Main
let uiModels = [UIModel(strValue: "32"), UIModel(strValue: "45")]
let models = uiModels.models()
print(models.map { $0.value })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment