티스토리 뷰
비즈니스 로직?
우리 눈에 보이지 않아도 되는 기능들
ex) 로그인 관련 기능
- 버튼을 눌렀을 때 판단하는 기능들
- → “@” 기호가 있는지, 한글이 섞여 있는지 등 판별하는 기능
ex) 상품 구매하기 버튼
- 구매를 못했을 때를 판단하는 기능들
- → 체크카드 만료, 계좌에 돈이 없음 등..
하나의 액션에 많은 기능들이 구현되어있음 → viewmodel로 빼보자
@objc private func amountChanged() {
print(#function)
//1. optional binding
guard let amountText = amountTextField.text else { return }
//2. isEmpty?
if amountText.isEmpty {
formattedAmountLabel.text = "값을 입력해주세요."
convertedAmountLabel.text = "값을 입력해주세요."
}
//3. is Number?
guard let amount = Int(amountText) else { return }
//4. validate Number
if amount > 0, amount <= 10000000 {
//5. formatted Number
let format = NumberFormatter()
format.numberStyle = .decimal
let wonResult = format.string(from: amount as NSNumber)!
formattedAmountLabel.text = "₩" + wonResult
let converted = Double(amount) / exchangeRate
let convertedFormat = NumberFormatter()
convertedFormat.numberStyle = .currency
convertedFormat.currencyCode = "USD"
let convertedResult = convertedFormat.string(from: converted as NSNumber)
convertedAmountLabel.text = convertedResult
} else {
formattedAmountLabel.text = "1,000만원 이하를 입력해주세요."
convertedAmountLabel.text = "1,000만원 이하를 입력해주세요."
}
}
ViewModel
1. 함수 분리→VC: ViewModel에 있는 validate함수를 내가 호출해야 함?VC에서 VM에 있는 함수를 호출하나 VC에서 직접 정의해서 호출하나 같음
func validation(_ value: String?) -> String {
//1. optional binding
guard let amountText = value else { return "" }
//2. isEmpty?
if amountText.isEmpty {
return "값을 입력해주세요."
}
//3. is Number?
guard let amount = Int(amountText) else { return "숫자만 입력해주세요." }
//4. validate Number
if amount > 0, amount <= 10000000 {
//5. formatted Number
let format = NumberFormatter()
format.numberStyle = .decimal
let wonResult = format.string(from: amount as NSNumber)!
return "₩" + wonResult
} else {
return "1,000만원 이하를 입력해주세요."
}
}
2. 프로퍼티로 관리하기 (input, output)
@objc private func amountChanged() {
formattedAmountLabel.text = viewModel.outputAmount
}
→ viewModel에 Property를 만들어서 VC가 VM의 property로 접근하기
VC에서는 VM에게 신호만 전달!
'🍎 iOS' 카테고리의 다른 글
| RxSwift vs Combine (0) | 2024.09.10 |
|---|---|
| RxSwift(1) (0) | 2024.07.30 |
| Compositional Layout - CollectionView(System설정) (0) | 2024.07.19 |
| Method Dispatch (0) | 2024.07.15 |
| Design Pattern (0) | 2024.07.14 |