본문 바로가기
Swift

알쓸스잡 - 3

by songmoro 2024. 12. 30.
728x90

나머지 연산자

나머지 연산자 %는 정수에서만 사용 가능

let x = 10
let y = 3

print(x % y)
// 1

 

소수에서 나머지 연산을 하기 위해선 다른 연산자 사용

  • remainder(dividingBy: )
  • truncatingRemainder(dividingBy: )
  • formRemainder(dividingBy: )
  • formTruncatingRemainder(dividingBy: )
let a = 10.0
let b = 3.0

print(a % b) 
// %' is unavailable: For floating point numbers use truncatingRemainder instead

 

튜플 비교 연산자

Swift에서는 튜플 간 값 비교를 지원

(1, "zebra") < (2, "apple")
// true because 1 is less than 2; "zebra" and "apple" are not compared

(3, "apple") < (3, "bird")
// true because 3 is equal to 3, and "apple" is less than "bird"

(4, "dog") == (4, "dog")
// true because 4 is equal to 4, and "dog" is equal to "dog"

 

튜플 간 값 비교는 최대 6개까지 지원

  • 7개 이상부터는 따로 Comparable로 구현
let a = (1, 2, 3, 4, 5, 6) == (1, 2, 3, 4, 5, 6)
// true

let b = (1, 2, 3, 4, 5, 6, 7) == (1, 2, 3, 4, 5, 6, 7)
// binary operator '==' cannot be applied to two '(Int, Int, Int, Int, Int, Int, Int)' operands

 

문자열 비교 연산

문자열의 크기는 앞 글자의 크기로 비교

  • 알파벳 순으로 크기가 커짐
    • a < b
  • 앞 글자부터 순차적으로 비교해서 길이에 상관없음
print("a" < "b") // true
print("ab" < "ba") // true
print("aa" <= "ab") // true
print("ab" <= "aa") // false
print("a" < "ab") // true
print("b" < "ab") // false
print("a" < "zzzzz") // true
print("z" < "aaaaa") // false

 

구현부

/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
///   - lhs: A value to compare.
///   - rhs: Another value to compare.
@inlinable public static func < <RHS>(lhs: String, rhs: RHS) -> Bool where RHS : StringProtocol

/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// - Parameters:
///   - lhs: A value to compare.
///   - rhs: Another value to compare.
@inlinable public static func > <RHS>(lhs: String, rhs: RHS) -> Bool where RHS : StringProtocol

 

참고

https://bbiguduk.github.io/swift-book-korean/documentation/the-swift-programming-language-korean/basicoperators
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators

728x90

'Swift' 카테고리의 다른 글

알쓸스잡 - 5  (0) 2025.01.17
알쓸스잡 - 4  (0) 2024.12.30
알쓸스잡 - 2  (0) 2024.12.26
알쓸스잡 - 1  (2) 2024.12.25
SwiftUI + Combine MVVM 아키텍쳐 분석 - 7  (0) 2024.11.11