-
swift - Extension #5 (Adding Subscript)swift 2021. 1. 12. 17:30
Adding Subscript
extension String { // 문자열 기본 인덱스는 정수 인덱스를 인덱스로 전달할 수 없다 반드시 문자열 인덱스를 전달해야함 subscript(idx: Int) -> String?{ guard (0..<count).contains(idx) else { return nil } let target = index(startIndex, offsetBy: idx) return String(self[target]) } } let str = "Swift" str[1] str[100] // nil extension Date { subscript(component: Calendar.Component) -> Int? { let cal = Calendar.current return cal.component(component, from: self) } } let today = Date() today[.year] today[.month] today[.day]
'swift' 카테고리의 다른 글
swift - Protocols #2 (Property Requirements) (0) 2021.01.12 swift - Protocols #1 (Syntax) (0) 2021.01.12 swift - Extension #4 (Adding Initializer) (0) 2021.01.12 swift - Extension #3 (Adding Method) (0) 2021.01.12 swift - Extension #2 (Adding Properties) (0) 2021.01.12