取下标

String

String 用 String.Index 取下标(subscript)得到 Character,String.Index 要从 String 中获取

let greeting = "Guten Tag!"greeting[greeting.startIndex] // Character "G"greeting[greeting.index(before: greeting.endIndex)] // Character "!"greeting[greeting.index(after: greeting.startIndex)] // Character "u"let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index] // Character "a"

String 用 Range<String.Index> 或 ClosedRange<String.Index> (以下 Range 和 ClosedRange 统称为 Range) 取下标得到 String

let str = "abc"str[str.startIndex..<str.index(after: str.startIndex)] // String "a"str[str.startIndex...str.index(after: str.startIndex)] // String "ab"

Character

网友评论