// // StringSubScript.swift // WOKA // // Created by MacBook Pro on 29/04/24. // import Foundation /* The first subscript allows you to access an element at a specific offset in the string. The next two subscripts allow you to get a subsequence using a range (open or closed). The last three subscripts handle partial ranges, providing a subsequence from the start, up to a specified index, or from a specified index to the end. */ import Foundation extension StringProtocol { subscript(_ offset: Int) -> Element { self[index(startIndex, offsetBy: offset)] } subscript(_ range: Range) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) } subscript(_ range: ClosedRange) -> SubSequence { prefix(range.lowerBound+range.count).suffix(range.count) } subscript(_ range: PartialRangeThrough) -> SubSequence { prefix(range.upperBound.advanced(by: 1)) } subscript(_ range: PartialRangeUpTo) -> SubSequence { prefix(range.upperBound) } subscript(_ range: PartialRangeFrom) -> SubSequence { suffix(Swift.max(0, count-range.lowerBound)) } } extension LosslessStringConvertible { var string: String { .init(self) } } extension BidirectionalCollection { subscript(safe offset: Int) -> Element? { if offset < 0 { return nil } guard !isEmpty, let i = index(startIndex, offsetBy: offset, limitedBy: index(before: endIndex)) else { return nil } return self[i] } } /* let test = "Hello USA πŸ‡ΊπŸ‡Έ!!! Hello Brazil πŸ‡§πŸ‡·!!!" test[safe: 10] // "πŸ‡ΊπŸ‡Έ" test[11] // "!" test[10...] // "πŸ‡ΊπŸ‡Έ!!! Hello Brazil πŸ‡§πŸ‡·!!!" test[10..<12] // "πŸ‡ΊπŸ‡Έ!" test[10...12] // "πŸ‡ΊπŸ‡Έ!!" test[...10] // "Hello USA πŸ‡ΊπŸ‡Έ" test[..<10] // "Hello USA " test.first // "H" test.last // "!" // Subscripting the Substring test[...][...3] // "Hell" // Note that they all return a Substring of the original String. // To create a new String from a substring test[10...].string // "πŸ‡ΊπŸ‡Έ!!! Hello Brazil πŸ‡§πŸ‡·!!!" */