관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift 공식 문서] 27. Advanced Operators (overflow 연산자, 연산자 정의) 본문

swift 공식 문서

[iOS - swift 공식 문서] 27. Advanced Operators (overflow 연산자, 연산자 정의)

jake-kim 2021. 7. 29. 23:45

Overflow Operator

  • 단순히 +, -로 접근하면 overflow 런타임 에러 발생

  • overflow operator
    • 추가: &+
    • 빼기: &-
    • 곱셈: &*

ex) Int16의 범위는 -32768 ~ 32767

var potentialOverflow = Int16.max
print(potentialOverflow) // 32767
potentialOverflow = potentialOverflow &+ 1
print(potentialOverflow) // -32768

Operator method

  • 연산자 재정의: static func로 정의
struct Vectror2D {
    var x = 0.0, y = 0.0
}

extension Vectror2D {
    static func + (left: Vectror2D, right: Vectror2D) -> Vectror2D {
        return Vectror2D(x: left.x + right.x, y: left.y + right.y)
    }
}

let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
// combinedVector is a Vector2D instance with values of (5.0, 5.0)
  • prefix 정의: static prefix func로 정의
extension Vector2D {
    static prefix func - (vector: Vector2D) -> Vector2D {
        return Vector2D(x: -vector.x, y: -vector.y)
    }
}

let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
// negative is a Vector2D instance with values of (-3.0, -4.0)
let alsoPositive = -negative
// alsoPositive is a Vector2D instance with values of (3.0, 4.0)

Compound Assignment Operators

  • Compound Assignment Operators: =와 다른 연산자를 결합한 형태
extension Vector2D {
    static func += (left: inout Vector2D, right: Vector2D) {
        left = left + right
    }
}

var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
// original now has values of (4.0, 6.0)

사용자 정의 연산자

  • Operator method와 동일하게 정의: static func 또는 static prefix func로 정의
extension Vector2D {
    static prefix func +++ (vector: inout Vector2D) -> Vector2D {
        vector += vector
        return vector
    }
}

var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// toBeDoubled now has values of (2.0, 8.0)
// afterDoubling also has values of (2.0, 8.0)
  • 연산자 우선순위 정의
    • 그룹에 연산자를 정의: infix, AdditionPrecedence
    • infix와 AdditionPrecedence란 그룹에 중위 연산자, +연산자 동일한 우선 순위 그룹으로 지정을 의미
infix operator +-: AdditionPrecedence
extension Vector2D {
    static func +- (left: Vector2D, right: Vector2D) -> Vector2D {
        return Vector2D(x: left.x + right.x, y: left.y - right.y)
    }
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
// plusMinusVector is a Vector2D instance with values of (4.0, -2.0)

* 참고

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

Comments