5. Not-Support Operators
let hello = "Hello"
let world = "World"
let greeting = hello + world
let noL = greeting - "l"
let world5 = world * 5
greeting[-1] == "d"
hello[1 ... 4] == "ello"
Binary operator '-' cannot be applied to two 'String' operands
Binary operator '*' cannot be applied to operands of type 'String' and 'Int'
'subscript(_:)' is unavailable: cannot subscript String with an Int, see the…
'subscript(_:)' is unavailable: cannot subscript String with an integer range, see …
7. Operators Overload
let hello = "Hello"
let world = "World"
let greeting = hello + world
let noL = greeting - "l" // HeoWord
let world5 = world * 5 // WorldWorldWorldWorldWorld
let text = greeting - "," - " " + "!" * 2 // HelloWorld!!
func - (_ origin: String, _ removal: String) -> String {
return origin.replacingOccurrences(of: removal, with: "")
}
func * (_ origin: String, _ times: Int) -> String {
return Array(1 ... times).map { _ in origin }.reduce("", +)
}
8. Extensions
let hello = "Hello"
let world = "World"
let greeting = hello + world
greeting[3] // "l"
greeting[-1] // "d"
extension String {
subscript(i: Int) -> Character {
var offset = i
while offset < 0 { offset += count }
let index = self.index(startIndex, offsetBy: offset)
return self[index]
}
}
9. Extensions
let hello = "Hello"
let world = "World"
let greeting = hello + world
hello[1 ... 4] // "ello"
hello[1 ..< 4] // "ell"
extension String {
subscript(_ range: CountableClosedRange<Int>) -> Substring {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = index(self.startIndex, offsetBy: range.upperBound)
return self[startIndex ... endIndex]
}
subscript(_ r: CountableRange<Int>) -> Substring {
let startIndex = index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex ..< endIndex]
}
}
12. Precedence Groups
Group Name Associativity Example Priority
BitwiseShiftPrecedence none << >>
Higher
Lower
MultiplicationPrecedence left * /
AdditionPrecedence left + -
RangeFormationPrecedence none … ..<
CastingPrecedence none as
NilCoalescingPrecedence right ??
ComparisonPrecedence none < <= > >= ==
LogicalConjunctionPrecedence left &&
LogicalDisjunctionPrecedence left ||
TernaryPrecedence right ? :
AssignmentPrecedence right += = *= -= /=
https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations
19. Q.
다음 중 custom operator 로 사용할 수 있는 것은?
① infix operator ~>: AdditionPrecedence
② infix operator ->: AdditionPrecedence
③ infix operator as: AdditionPrecedence
④ infix operator $$: AdditionPrecedence
29. Summary
1. Operator Overloading, Extension, Custom Operator
을 활용해서 기능을 추가할 수 있다.
2. Operator는 Precedence 에 의한 연산 우선순위가 적용된다.
3. value 뿐 아니라 function 에도 연산자를 적용할 수 있다.
4. 복잡할 수 있는 연산을 간결하게 표현할 수 있다.
5. 코드의 가독성을 높일 수 있다.
( ⚠ 과하면 오히려 가독성을 해칠 수 있다 )