🔵 옵셔널 제거 방법 3가지 💁🏻♀️
1. Forced Unwrapping (if you're sure it's safe) :
forced unwrapping('!')을 사용할 땐 주의해야 한다. 옵셔널이 'nil'일 경우, 시스템이 충돌하기 때문이다.
변환이 항상 성공하는 상황에서만 사용할 것!
let char: Character = "5"
// wholeNumberValue 뒤에 ! 붙이는 경우
let integerValue = char.wholeNumberValue!
print(integerValue) // 5
// 변수 뒤에 ! 붙이는 경우
let integerValue = char.wholeNumberValue
print(integerValue!) // 5
방법 : Optional로 선언된 변수(상수) 뒤에 !를 붙여주면 된다.
▽ [더보기] 클릭
더보기
예시 : a가 옵셔널 int라고 할 때,
var myInfo = "내 나이는 \(a!)살 입니다."
print(myInfo)
// 내 나이는 4살 입니다.
2. Optional Blinding:
if문을 사용하면 변환에 실패하는 경우를 적절히 처리할 수 있다.
let char: Character = "5"
if let integerValue = char.wholeNumberValue {
print(integerValue)
} else {
print("Conversion failed")
}
3. Nil Coalescing Operator:
이 경우, optional이 'nil'일 때 디폴트 값을 반환하게 한다.
아래 예시에서는 디폴트 값 = 0
let char: Character = "5"
let integerValue = char.wholeNumberValue ?? 0
print(integerValue)
☑️ 예제
https://yurim-dev.tistory.com/20
[Swift] Character를 Int로 변환하기 - .wholeNumberValue, Int(String(문자))
Character를 Int로 변환하는 방법으로 두 가지가 있는 듯하다. 🔵 1. 방법 1) .wholeNumberValue Property 사용 참고: apple developer 공식 문서(링크), tutorialspoint(링크) ▶ 1-1. 설명 whole Number Value property를 사용해
yurim-dev.tistory.com
'Swift > 문법' 카테고리의 다른 글
[Swift|문법] 조건문 - combining conditions(&&, ||), ternary operator(삼항 연산자), switch (0) | 2024.02.16 |
---|---|
[Swift] 연산자 (operator) - arithmetic, overloading, compound, comparison (0) | 2024.02.16 |
[Swift] 고차함수 - map 시리즈(map, flatMap, compactMap) (0) | 2024.02.14 |
[Swift] Character를 Int로 변환하기 - .wholeNumberValue, hexDigitValue, Int(String(문자)) (0) | 2024.02.07 |
[Swift] 고차함수 - map, filter, reduce (2) | 2024.02.07 |