Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reversing view models in Swift
import Foundation
import UIKit
struct CreditCard {
let number: String
let expirationDate: Date
}
class CreditCardView {
@IBOutlet private weak var numberTextView: UITextView!
@IBOutlet private weak var monthTextField: UITextField!
@IBOutlet private weak var yearTextField: UITextField!
var viewModel: ViewModel? {
didSet {
numberTextView.text = viewModel?.number
monthTextField.text = viewModel?.month
yearTextField.text = viewModel?.year
}
}
}
extension CreditCardView {
struct ViewModel {
let number: String
let month: String
let year: String
}
}
extension CreditCardView.ViewModel {
init(creditCard: CreditCard) {
number = creditCard.number.accountNumberFormatting
month = "\(creditCard.expirationDate.month)"
year = "\(creditCard.expirationDate.year)"
}
var creditCard: CreditCard {
let number = self.number.trimmingCharacters(in: .whitespaces)
let date = Date.from(month: Int(month)!, year: Int(year)!)
return CreditCard(number: number, expirationDate: date)
}
}
extension String {
var accountNumberFormatting: String {
var formattedString = ""
for (index, character) in enumerated() {
if index % 4 < 3 || index == count - 1 {
formattedString.append(character)
} else {
formattedString.append("\(character) ")
}
}
return formattedString
}
}
extension Date {
static func from(month: Int, year: Int) -> Date {
let calendar = NSCalendar.current
var components = DateComponents()
components.month = month
components.year = year
return calendar.date(from: components)!
}
var month: Int {
let calendar = NSCalendar.current
return calendar.component(.month, from: self)
}
var year: Int {
let calendar = NSCalendar.current
return calendar.component(.year, from: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment