Operator overloading
string끼리 +로 더하면 뒤에 붙음
array도 마찬가지로 앞 array에 value가 추가됨.
같은 것(Int + Int, String+String, …)끼리만 연산 가능.
Boolean끼리는 더할 수 없음.
Swift에는 제곱연산자가 없음.
Compound assignment operator
score -= 5 라는 코드는 score = score - 5와 같음.
Comparison operators
== -> equal (비교할 때에는 = 두 번 써야함)
!= -> not equal
< , >
string을 비교하면 알파벳 순서로 대소비교가 됨.
Condition
if … {
A코드
} else if … {
B코드
} else {
C코드
}
처음 ...조건이 true일 경우엔 A를 실행.
처음 조건이 틀리고 else if 뒤의 …가 true인 경우엔 B실행
위 두 조건이 모두 false라면 C를 실행.
Combining condition
&& -> and(비교대상 모두 true여야함)
|| -> or(비교대상 중 하나라도 true면 됨)
The ternary operator
? 와 : 를 이용하여 조건문 작성
if a == b {
print(“Same”)
} else {
print(“Different”)
}
위 코드와 아래의 코드는 같음.
Print(a == b ? “Same” : “Different”)
? 앞의 비교가 true일 경우엔 앞의 것을 출력, false일 경우엔 뒤의 것 출력.
Switch statements
if문에서 if else를 여러 번 쓰게 될 경우 switch가 더 보기 편함
let weather = "sunny"
switch weather {
case "rain":
print("Bring an umbrella")
case "snow":
print("Wrap up warm")
case "sunny":
print("Wear sunscreen")
default:
print("Enjoy your day!")
}
위의 경우에선 “sunny”case 안의 코드를 실행
다음 케이스로 continue하고 싶다면 fallthrough이용
모든 경우에 대해서 case가 나눠지는 것이 아니라면 default를 꼭 써줘야함.
Range operators
1이상 5이하 -> 1…5
1이상 5미만 -> 1..<5