애플 공식 문서 바탕으로 정리 합니다!
Operators are unary, binary, or ternary
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)
: 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.
(3, "apple") < (3, "bird")
// true because 3 is equal to 3, and "apple" is less than "bird"
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
}
: 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"
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