String.Index

โญ๏ธ ๆณจๆ„๏ผš

ไฝฟ็”จ str[index] ๆ™‚๏ผŒๆœ‰ไธ€ๅ€‹ใ€Œ้šฑ่—็š„้›ทๅ€ใ€๏ผš้›–็„ถ endIndex ๆ˜ฏไธ€ๅ€‹ valid String.Index ไฝ†ๅฆ‚ๆžœไฝฟ็”จ str[str.endIndex] ้ฆฌไธŠๆœƒ้€ ๆˆ crashโ—๏ธๅฐคๅ…ถๆ˜ฏไฝฟ็”จ๏ผš

str.index(_:offsetBy:limitedBy:)

็š„ๆ™‚ๅ€™่ฆๅฐๅฟƒ๏ผŒไธ่ฆๅƒๅฎ˜็ถฒ้€™ๆจฃๅฏซ๏ผš

// offset: 01234
let s  =  "Swift"
//           โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โญ๏ธ offset = 5 ๆœƒๅพ—ๅˆฐ endIndexโ—๏ธ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
if let i = s.index(s.startIndex, offsetBy: 5, limitedBy: s.endIndex) {
    print(s[i])    // ๐Ÿ’ฅ ้€™่ฃกๅฐฑๆœƒ้€ฒๅ…ฅใ€Œ้›ทๅ€ใ€
}
let str = "apple,pear,peach,orange,cherry,lime,goosberry"

// โญ๏ธ String.Index
let i = str.index(str.startIndex, offsetBy: 2)    
let j = str.index(str.startIndex, offsetBy: 10)
// โญ๏ธ ๆณจๆ„๏ผš
//    ๅœจ้€™่ฃก๏ผŒๅช่ฆ offset ่ถ…ๅ‡บๅˆ็†็ฏ„ๅœ๏ผŒๅฐฑๆœƒ็”ข็”Ÿไธ‹ๅˆ—้Œฏ่ชค๏ผš
//    ใ€Œโ›” Fatal error: String index is out of boundsใ€
//    ็›ดๆŽฅ้€ ๆˆ crash๏ผŒไธ้œ€็ญ‰ๅˆฐๆ”พๅˆฐ subscript ไธญ (ๅฆ‚๏ผš`str[i]`)ใ€‚

// โญ๏ธ ๅฐฑ็ฎ—ไฝฟ็”จ str.index(_:offsetBy:limitedBy:) ็š„็‰ˆๆœฌ๏ผŒ
//    ๅฆ‚ๆžœใ€Œๆ“‹้Œฏ้‚Šใ€๏ผŒไธ€ๆจฃๆœƒ crashโ—๏ธไพ‹ๅฆ‚๏ผš
let index = str.index(
    str.startIndex, 
    offsetBy: -2, 
    limitedBy: str.endIndex    // โญ๏ธ ๆ“‹้Œฏ้‚Šโ—๏ธ
)

str[i]        // โญ๏ธ Character: "p"
str[i..<j]    // โญ๏ธ Substring: "ple,pear"

Last updated