Created
March 19, 2017 23:14
-
-
Save hamsternik/fc457b134193b7d5754e72e79b7b51eb to your computer and use it in GitHub Desktop.
Transform UIModel object to the Model using protocols
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 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