1. 마지막 공백의 index를 구한다.
번지수 앞에는 항상 공백이 있고 그 공백은 전체 String에서 가장 마지막에 위치하는 공백이다.
let lastBlankIndex = address.lastIndex(of: " ")
2. 첫 글자와 마지막 공백 사이의 거리를 구한다.
let distance = address.distance(from: startIndex, to: lastBlankIndex)
3. 전체 String 길이에서 첫 글자와 마지막 공백 사이의 거리를 뺀다.
dropLast를 하기 위해서 맨 뒤 글자를 기준으로 한 마지막 공백의 위치를 알아내야 하기 때문.
let dropLastPosition = address.count - distance
4. 'dropLast'를 이용해 마지막 공백부터 나머지 글자를 잘라낸다.
address.dropLast(dropLastPosition)
5. String 타입으로 변환한다.
'dropLast'한 String은 'String.SubSequence' 타입이 되기 때문에 String으로 다시 변환해주어야 한다.
String(simpleAddress)
6. Example
let address = "서울 중구 세종대로 110"
func getSimpleAddress(address: String) -> String? {
guard let lastBlankIndex = address.lastIndex(of: " ") else { return nil }
let startIndex = address.startIndex
let distance = address.distance(from: startIndex, to: lastBlankIndex)
let dropLastPosition = address.count - distance
let simpleAddress = address.dropLast(dropLastPosition)
return String(simpleAddress)
}
getSimpleAddress(address: address) /// return "서울 중구 세종대로"
dropLast, lastIndex 뿐만 아니라 dropFirst, firstIndex, components, split 등 다양한 방법으로 String을 수정할 수 있다.