
ตัวอย่างทั้งหมดต่อไปนี้ใช้
var str = "Hello, playground"
startIndex และ endIndex
startIndex คือดัชนีของอักขระตัวแรก
endIndexคือดัชนีหลังอักขระสุดท้าย
ตัวอย่าง
// character
str[str.startIndex] // H
str[str.endIndex] // error: after last character
// range
let range = str.startIndex..<str.endIndex
str[range] // "Hello, playground"
ด้วยช่วงด้านเดียวของ Swift 4 ช่วงสามารถทำให้ง่ายขึ้นเป็นหนึ่งในรูปแบบต่อไปนี้
let range = str.startIndex...
let range = ..<str.endIndex
ฉันจะใช้แบบฟอร์มเต็มในตัวอย่างต่อไปนี้เพื่อความชัดเจน แต่เพื่อประโยชน์ในการอ่านคุณอาจต้องการใช้ช่วงด้านเดียวในโค้ดของคุณ
after
ใน: index(after: String.Index)
after หมายถึงดัชนีของอักขระโดยตรงหลังดัชนีที่กำหนด
ตัวอย่าง
// character
let index = str.index(after: str.startIndex)
str[index] // "e"
// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range] // "ello, playground"
before
ใน: index(before: String.Index)
before หมายถึงดัชนีของอักขระโดยตรงก่อนดัชนีที่กำหนด
ตัวอย่าง
// character
let index = str.index(before: str.endIndex)
str[index] // d
// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range] // Hello, playgroun
offsetBy
ใน: index(String.Index, offsetBy: String.IndexDistance)
offsetByค่าสามารถบวกหรือเชิงลบและเริ่มต้นจากดัชนีที่กำหนด แม้ว่าจะเป็นประเภทใดString.IndexDistanceก็ตามคุณสามารถระบุไฟล์Int.
ตัวอย่าง
// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index] // p
// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range] // play
limitedBy
ใน: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)
- สิ่ง
limitedByนี้มีประโยชน์ในการตรวจสอบให้แน่ใจว่าการชดเชยไม่ทำให้ดัชนีหลุดออกไปนอกขอบเขต มันเป็นดัชนีขอบเขต เนื่องจากเป็นไปได้ที่ค่าชดเชยจะเกินขีด จำกัด เมธอดนี้จะส่งคืนตัวเลือก จะส่งคืนnilหากดัชนีอยู่นอกขอบเขต
ตัวอย่าง
// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
str[index] // p
}
หากได้รับการชดเชย77แทน7แล้วifคำสั่งจะได้รับข้าม
ทำไมต้องใช้ String.Index?
การใช้ดัชนีสำหรับ Strings จะง่ายกว่ามาก Intเหตุผลที่คุณต้องสร้างใหม่String.Indexสำหรับทุก String คือตัวอักษรใน Swift มีความยาวไม่เท่ากันทั้งหมดภายใต้ประทุน อักขระ Swift ตัวเดียวอาจประกอบด้วยจุดรหัส Unicode หนึ่งสองจุดหรือมากกว่านั้น ดังนั้นแต่ละสตริงที่ไม่ซ้ำกันจะต้องคำนวณดัชนีของอักขระ
เป็นไปได้ที่จะซ่อนความซับซ้อนนี้ไว้เบื้องหลังส่วนขยายดัชนี Int แต่ฉันไม่เต็มใจที่จะทำเช่นนั้น เป็นการดีที่จะได้รับการแจ้งเตือนถึงสิ่งที่เกิดขึ้นจริง
startIndexเป็นอย่างอื่นที่ไม่ใช่ 0?