Swiftの部分文字列の取得が面倒なので、簡単にするためのextensionを作成しました。
動作確認はSwift 5ですが、4から有効です。
/// String extension for convenient of substring
extension String {
/// Index with using position of Int type
func index(at position: Int) -> String.Index {
return index((position.signum() >= 0 ? startIndex : endIndex), offsetBy: position)
}
/// Subscript for using like a "string[i]"
subscript (position: Int) -> String {
let i = index(at: position)
return String(self[i])
}
/// Subscript for using like a "string[start..<end]"
subscript (bounds: CountableRange<Int>) -> String {
let start = index(at: bounds.lowerBound)
let end = index(at: bounds.upperBound)
return String(self[start..<end])
}
/// Subscript for using like a "string[start...end]"
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(at: bounds.lowerBound)
let end = index(at: bounds.upperBound)
return String(self[start...end])
}
/// Subscript for using like a "string[..<end]"
subscript (bounds: PartialRangeUpTo<Int>) -> String {
let i = index(at: bounds.upperBound)
return String(prefix(upTo: i))
}
/// Subscript for using like a "string[...end]"
subscript (bounds: PartialRangeThrough<Int>) -> String {
let i = index(at: bounds.upperBound)
return String(prefix(through: i))
}
/// Subscript for using like a "string[start...]"
subscript (bounds: PartialRangeFrom<Int>) -> String {
let i = index(at: bounds.lowerBound)
return String(suffix(from: i))
}
}
使用例
let string = "0123456789"
print(string[3]) // -> "3"
print(string[-3]) // -> "7"
print(string[1...5]) // -> "12345"
print(string[1..<5]) // -> "1234"
print(string[...5]) // -> "012345"
print(string[...(-3)]) // -> "01234567"
print(string[..<5]) // -> "01234"
print(string[..<(-3)]) // -> "0123456"
print(string[5...]) // -> "56789"
print(string[(-3)...]) // -> "789"