공부/SWIFT

[SWIFT] 연산자에서 알아둬야 할것(Operator)

알로하리미 2021. 3. 10. 10:05
728x90

아주 기본적인 내용은 제외.

 

1. 할당연산자(assignment operator)

let b = 10
var a = 5
a = b
// a is now equal to 10

//튜플의 할당
let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2


//C 및 Objective-C의 할당 연산자와 달리 Swift의 할당 연산자는 자체적으로 값을 반환하지 않습니다
if x = y {
    //유효하지 않습니다.
}
//이 기능 =은 같음 연산자 ( ==)가 실제로 의도 된 경우 
//할당 연산자가 실수로 사용되는 것을 방지합니다 . 
//무효화 함으로써 Swift는 코드에서 이러한 종류의 오류를 피하는 데 도움이됩니다.if x = y

 

 

2. 산술연산자(arithmetic operators)

- 나머지 연산자

10 % 4      // 나머지 equals 2

- 부동소수점 타입 나머지 연산 하기

//부동소수점 타입 나머지 연산
let number: Double = 5.0
var result: Double = number.trncatingRemainder(dividingBy: 1.5) //0.5
result = 12.truncatingRemainder(dividingBy: 2.5)                //2.5

 

 

3. 비교연산자

- 7 개 미만인 튜플에 대한 튜플 비교 연산자가 포함되어 있습니다. 7 개 이상의 요소가있는 튜플을 비교하려면 비교 연산자를 직접 구현

//유형이 같고 값 수가 같은 경우 두 튜플을 비교할 수 있습니다.

(1, "zebra") < (2, "apple")   
// true because 1 is less than 2; "zebra" and "apple" aren't 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"

("blue", -1) < ("purple", 1)        
// OK, evaluates to true

("blue", false) < ("purple", true)  
// Error because < can't compare Boolean values

- Swift는 객체 비교를 위해 식별 연산자 ===  !==를 제공

let A: SomeClass = SomeClass()
let B: SomeClass = SomeClass()
let C: SomeClass = A

let isSameReferenceAB: Bool = referenceA === referenceB // false
let isSameReferenceAC: Bool = referenceA === referenceC // true

 

 

4. 삼항 조건 연산자

question ? answer1 : answer2

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight는 90 (40 + 50)

* 너무 남발하면 중첩사용하면 가독성이 떨어진다.

 

 

5. 범위 연산자

// 닫힌 범위 연산자(Closed Range Operator) 
// (a...b)의 형태 for-in loop에 자주 사용
for index in 1...5 {
    print(index)
}



// 반 닫힌 범위 연산자(Half-Open Range Operator)
// (a..<b)의 형태로 a부터 b보다 작을 때까지의 범위
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack



// 단방향 범위 연산자(One-Side Ranges) 
// [a...] [...a]의 형태로 범위의 시작 혹은 끝만 지정해 사용
for name in names[2...] {
    print(name)
}
// Brian
// Jack


for name in names[...2] {
    print(name)
}
// Anna
// Alex
// Brian


for name in names[..<2] {
    print(name)
}
// Anna
// Alex




// 단방향 범위 연산자는 subscript뿐만 아니라 
// 아래와 같이 특정 값을 포함하는지 여부를 확인할 때도 사용 가능합니다.
let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

 

 

6. 비트 연산자

- 비트 연산자 NOT ( ~A ) : 비트를 뒤집는다.

//2비트 표현시 앞에 0b를 붙인다
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits  // equals 11110000

- 비트 연산자 AND ( A&B ) : 두 비트가 같은 값인 경우 1 다른경우 0으로 변환

let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8  = 0b00111111
let middleFourBits = firstSixBits & lastSixBits  // equals 00111100

- 비트 연산자 OR( A|B ) : 비트 연산자 OR는 두 비트중 하나라도 1이면 1 값을 갖습니다.

let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits  // equals 11111110

- 비트 연산자 XOR(A^B) : 두 비트가 다른 경우에 1, 같은 경우에 0을 갖습니다.

let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits  // equals 00010001

- 비트시프트연산자(비트이동연산자)

비트를 왼쪽(A<<B) 혹은 오른쪽(A>>B)으로 미는 시프트 연산자

let shiftBits: UInt8 = 4   // 00000100 in binary
shiftBits << 1             // 00001000
shiftBits << 2             // 00010000
shiftBits << 5             // 10000000
shiftBits << 6             // 00000000
shiftBits >> 2             // 00000001

* 범위를 벗어난 비트는 버려집니다.

 

 

7.복합할당연산자

A += B A = A + B
A -= B A = A - B
A *= B A = A * B
A /= B A = A / B
A %= B A = A % B
A <<= B A = A << B
A >>= B A = A >> B
A &= B A = A & B
A |= B A = A | B
A ^= B A = A ^ B

 

 

8. 기타 연산자

nil 병합 연산자  A ?? B  A가 nil이 아니면 A를 반환하고, A가 nil이면 B를 반환
부호변경연산자 -A A의 부호를 변경
옵셔널 강제 추출 연산자 O! O(옵셔널개체)의 값을 강제로 추출 (사용지양)
옵셔널 연산자 V? V(옵셔널값)을 안전하게 추출하건, V(데이터타입)가 옵셔널임을 표현

 

 

9. 사용자 정의 연산자

[기존 연산자] ( 삼항연산자 (?), 할당연산자( = ) 빼고 )들을 재정의 하거나 [새로운 기호]들을 사용해 사용자 정의 연산자를 만들 수있다.

prefix 전위, infix 중위, postfix 후위 로 새로운 연산자를 설정할 수 있다.

연산자의 우선순위를 지정 할 수 있다. 

하나의 피연산자에 전위 연산과 후위연산을 한줄에 사용하면 후위연산을 먼저 수행

ex) infix operator ** : MultiplicationPrecedence 

* 중위 연산자를 정의할 때 우선순위 그룹을 명시해지주지 않으면 운선순위가 가장 높음 DeafultPrecedence그룹을 우선순위 그룹으로 갖게 됩니다.

만약 특정타입에 국한된 연산자 함수라면 그 타입 내부에 구현되는것이 옳다.

 

extension Vector2D {
    static prefix func - (vector: Vector2D) -> Vector2D {
        return Vector2D(x: -vector.x, y: -vector.y)
    }
}

//Vector2D 에서 Vector2D를 매개변수로 받으면
//-Vector2D 사용시에
//Vector2D의 속성값에 음수로 변환하여 새로운 Vector2D를 반환한다..

let positive = Vector2D(x: 3.0, y: 4.0) //인스턴스생성
// positive의 x,y값을 (-)변환하여 새로운 instance생성
let negative = -positive
// negative is a Vector2D instance with values of (-3.0, -4.0)
let alsoPositive = -negative


//+=연산자 재정의
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)



//전방위 연산자 +++ 정의 prefix 전위, infix 중위, postfix 후위
prefix operator +++

//+++를 사용하면 2배의 값을 갖게 +++ 함수선언
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)

 

우선순위
연산자 우선순위 그룹이름 결합 방향 할당 방향 사용
DefaultPrecedence none fasle
BitwiseShiftPrecedence none fasle
MultiplicationPrecedence left fasle
AdditionPrecedence left fasle
RangeFormationPrecedence none fasle
CastingPrecedence none fasle
ComparisonPrecedence right fasle
LogicalConjunctionPrecedence none fasle
LogicalDisjunctionPrecedence left fasle
TernaryPrecedence left fasle
AssignmentPrecedence right true
FunctionArrowPrecedence right fasle

 

<<

Bitwise left shift

None

BitwiseShiftPrecedence

>>

Bitwise right shift

None

BitwiseShiftPrecedence

*

Multiply

Left associative

MultiplicationPrecedence

/

Divide

Left associative

MultiplicationPrecedence

%

Remainder

Left associative

MultiplicationPrecedence

&*

Multiply, ignoring overflow

Left associative

MultiplicationPrecedence

&

Bitwise AND

Left associative

MultiplicationPrecedence

+

Add

Left associative

AdditionPrecedence

-

Subtract

Left associative

AdditionPrecedence

&+

Add with overflow

Left associative

AdditionPrecedence

&-

Subtract with overflow

Left associative

AdditionPrecedence

|

Bitwise OR

Left associative

AdditionPrecedence

^

Bitwise XOR

Left associative

AdditionPrecedence

..<

Half-open range

None

RangeFormationPrecedence

...

Closed range

None

RangeFormationPrecedence

is

Type check

Left associative

CastingPrecedence

as, as?, and as!

Type cast

Left associative

CastingPrecedence

??

Nil coalescing

Right associative

NilCoalescingPrecedence

<

Less than

None

ComparisonPrecedence

<=

Less than or equal

None

ComparisonPrecedence

>

Greater than

None

ComparisonPrecedence

>=

Greater than or equal

None

ComparisonPrecedence

==

Equal

None

ComparisonPrecedence

!=

Not equal

None

ComparisonPrecedence

===

Identical

None

ComparisonPrecedence

!==

Not identical

None

ComparisonPrecedence

~=

Pattern match

None

ComparisonPrecedence

.==

Pointwise equal

None

ComparisonPrecedence

.!=

Pointwise not equal

None

ComparisonPrecedence

.<

Pointwise less than

None

ComparisonPrecedence

.<=

Pointwise less than or equal

None

ComparisonPrecedence

.>

Pointwise greater than

None

ComparisonPrecedence

.>=

Pointwise greater than or equal

None

ComparisonPrecedence

&&

Logical AND

Left associative

LogicalConjunctionPrecedence

||

Logical OR

Left associative

LogicalDisjunctionPrecedence

?:

Ternary conditional

Right associative

TernaryPrecedence

=

Assign

Right associative

AssignmentPrecedence

*=

Multiply and assign

Right associative

AssignmentPrecedence

/=

Divide and assign

Right associative

AssignmentPrecedence

%=

Remainder and assign

Right associative

AssignmentPrecedence

+=

Add and assign

Right associative

AssignmentPrecedence

-=

Subtract and assign

Right associative

AssignmentPrecedence

<<=

Left bit shift and assign

Right associative

AssignmentPrecedence

>>=

Right bit shift and assign

Right associative

AssignmentPrecedence

&=

Bitwise AND and assign

Right associative

AssignmentPrecedence

|=

Bitwise OR and assign

Right associative

AssignmentPrecedence

^=

Bitwise XOR and assign

Right associative

AssignmentPrecedence

 

 

 

'공부 > SWIFT' 카테고리의 다른 글

[SWIFT] 제어문( 반복문 for-in )  (0) 2021.03.10
[SWIFT] 제어문(조건문 if , switch)  (0) 2021.03.10
[SWIFT] 열거형 (enum)  (0) 2021.03.09
[SWIFT] 컬렉션형 - 세트(Set)  (0) 2021.03.09
[SWIFT] 컬렉션형 - 딕셔너리(Dictionary)  (0) 2021.03.09