Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Structures and Classes
- 스타트업주니어로살아남기
- SWIFTUI
- 독서후기
- Navigation
- human interface guidelines
- 아이폰
- Failed to register bundle identifier
- 부트캠프
- Info.plist
- 독후감
- Codegen
- Modality
- contentInset
- viewcontroller
- NotificationCenter
- xcode
- delegation
- SWIFT
- 스위프트
- UIResponder
- roundingMode
- 책후기
- @available
- 야곰아카데미
- NumberFormatter
- Mock
- View Life Cycle
- IOS
- mvvm
Archives
- Today
- Total
호댕의 iOS 개발
[Swift 기본 문법] Double에선 %(모듈로) 대신 .truncatingRemainder(dividingBy:)!! 본문
Software Engineering/Swift
[Swift 기본 문법] Double에선 %(모듈로) 대신 .truncatingRemainder(dividingBy:)!!
호르댕댕댕 2022. 6. 3. 11:21
프로젝트를 진행하면서 소수점 값이 존재하는지 확인할 필요가 있었다.
그래서 Double 타입에서 %(모듈로) 연산자를 통해 1로 나눈 나머지가 있는지 확인하려 했다.
그런데 왠걸?!
이런 에러를 만났다.
'%' is unavailable: For floating point numbers use truncatingRemainder instead
사실 에러를 보면 간단하게 해결이 가능하다.
%(모듈로) 연산자는 Int에만 정의가 되어 있기 때문에 Double에선 사용이 불가능했던 것이다.
public static func % (lhs: Int, rhs: Int) -> Int
알고나면 진짜 간단하지만 갑자기 에러가 뜨면 당황할 수도 있기에...
그래서 다음과 같이 정의되어있는 함수 .truncatingRemainder(dividingBy:)를 사용해주면 모듈로 연산자와 동일하게 사용이 가능하다.
private func createStarRating(from rating: Double) {
let roundedRating = round(rating * 10) / 10
// roundedRating % 1 == 0 Double이라 모듈로 연산자 존재 X
if roundedRating.truncatingRemainder(dividingBy: 1) == 0 { // 소수점이 없는 경우
}
}
'Software Engineering > Swift' 카테고리의 다른 글
Comments