[Swift] Basic Operators

East Silver·2021년 12월 25일
0

애플 공식 문서 바탕으로 정리 합니다!

Basic Operators

Operators are unary, binary, or ternary

Assignment Operator

The assignment operator (a = b) initializes or updates the value of a with the value of b

let b = 10
var a = 5
let (x, y) = (1, 2)

Arithmetic Operators

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

Remainder Operator

: The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that’s left over (known as the remainder).
a = (b x some multiplier) + remainder

9 % 4  //1
9 % -4 //1
9 % 4  //1
-9 % 4 //-1

The sign of b(==-4) is ignored for negative values of b. This means that a % b and a % -b always give the same answer.

Comparison Operators

  • Equal to (a == b)
  • Not equal to (a != b)
  • Greater than (a > b)
  • Less than (a < b)
  • Greater than or equal to (a >= b)
  • Less than or equal to (a <= b)
    Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.
(3, "apple") < (3, "bird") 
// true because 3 is equal to 3, and "apple" is less than "bird"

Ternary Conditional Operator

question ? answer1 : answer2.
If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.
answer의 타입은 같아야 한다
The ternary conditional operator is shorthand for the code below:

if question {
    answer1
} else {
    answer2
}

Nil-Coalescing Operator

: a ?? b 와 같은 연산자로 옵셔널을 분석할 때 사용한다. 옵셔널에 값이 저장되어 있지 않을 때 사용할 값을 지정하는 방법이다.
a와 b는 같은 데이터 타입!

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName isn't nil, so colorNameToUse is set to "green"

Range Operators

Closed Range Operator

for index in 1...5 {
	print(index) // 1 2 3 4 5
}

Half-Open Range Operator

for index in 1..<5 {
	print(index) // 1 2 3 4
}

One-Sided Ranges
숫자와 점들 사이에 공백없이 작성해야한다.

for name in names[2...] {
}

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

let range = ...5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

Logical Operators

  • Logical NOT (!a)
  • Logical AND (a && b)
  • Logical OR (a || b)
profile
IOS programmer가 되고 싶다

0개의 댓글