버그 잡이

Swift - .allSatisfy() 로 array 검증하기 (feat. 약관 전체 동의) 본문

카테고리 없음

Swift - .allSatisfy() 로 array 검증하기 (feat. 약관 전체 동의)

버그잡이 2021. 8. 24. 21:06

 

allSatisfy 기본 개념

 

Array의 모든 요소를 검증하고 싶을때 일반적으로는 for문을 활용해서 검증할 수 있습니다.

let evenNumbers = [1, 3, 5, 7, 9]

for number in evenNumbers {
	if number % 2 == 0 {
    	return false
    }
}

return true

 

.allSatisfy 를 활용하면 for문 없이 코드 작성이 가능합니다.

let evenNumbers = [1, 3, 5, 7, 9]
let allMatch = evenNumbers.allSatisfy { $0 % 2 == 1 }

print(allMatch) // true

 

 

allSatisfy로 회원가입 약관 검증하기

 

회원가입 약관은 보통 상위 약관과 상위 약관 아래의 하위 약관으로 구성되어있습니다.

1. 개인정보 정책 모두 동의
    1-1) 개인 정보 수집
    1-2) 개인 정보 열람

2. 마케팅 약관 모두 동의
    2-1) 이메일
    2-2) 전화

 

위와 같은 구조는 아래와 같은 속성을 가집니다.

1) 상위 약관을 체크하면 하위 약관이 모두 체크 되고

2) 하위 약관이 모두 체크 되면 상위 약관도 체크 되는 구조입니다.

 

 

allSatisfy를 통해서 2번 로직 검증을 진행할 수 있습니다.

 

var allMarketingTermAgreed = false
var emailMarketingAgreed = false
var phoneMarketingAgreed = false

func updateAllMarketingTermAgreedStatus() {
    allMarketingTermAgreed = [emailMarketingAgreed, phoneMarketingAgreed].allSatisfy{ $0 }
}

 

email, phone 약관이 체크될때마다 updateAllMarketingTermAgreedStatus()로 allMarketingTermAgreed의 상태를 최신화 해줄 수 있습니다.

 

 

RxSwift를 쓴다면 구독을 통해서 매번 호출해줄 필요없이 allMarketingTermAgreed 상태를 최신화 해줄 수 있습니다.

var allMarketingTermAgreed = BehaviorRelay<Bool>(value: false)
var emailMarketingAgreed = BehaviorRelay<Bool>(value: false)
var phoneMarketingAgreed = BehaviorRelay<Bool>(value: false)

func binding() {
    Observable.combineLastest(emailMarketingAgreed, phoneMarketingAgreed)
    	.subscribe { emailAgreed, phoneAgreed in
            let allAgreed = [emailAgreed, phoneAgreed].allSatisfy{ $0 }
            allMarketingTermAgreed.accept(allAgreed)
        }
}

 

반응형
Comments