본문 바로가기

iOS

[Swift] Substring

반응형

만약 text를 자를 일이 있다면 아래와같이 코드블럭 추가해 주는게 편하다.

extension String {
    func substring(from: Int, to: Int) -> String {
        guard from < count, to >= 0, to - from >= 0 else {
            return ""
        }
        
        // Index 값 획득
        let startIndex = index(self.startIndex, offsetBy: from)
        let endIndex = index(self.startIndex, offsetBy: to + 1) // '+1'이 있는 이유: endIndex는 문자열의 마지막 그 다음을 가리키기 때문
        
        // 파싱
        return String(self[startIndex ..< endIndex])
    }
}

'iOS' 카테고리의 다른 글

[Swift] isUserInteractionEnabled  (0) 2022.01.24
[Swift] NotificationCenter  (0) 2022.01.12
[Swift] characteristic read, write  (0) 2022.01.06
[Swift] contentView - expandable tableView  (0) 2022.01.02
[Swift] Google Admob 추가  (0) 2021.12.24