Skip to content

Instantly share code, notes, and snippets.

@sstadelman
Last active May 11, 2019 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstadelman/67c16bc36144d995aaf152ca95e29218 to your computer and use it in GitHub Desktop.
Save sstadelman/67c16bc36144d995aaf152ca95e29218 to your computer and use it in GitHub Desktop.
String length bug
//
// Repro.swift
//
// Created by Stadelman, Stan on 5/10/19.
//
import Foundation
/// Sample bidirectional string, which happens to include neutral characters "(" and ")"
/// String source: [Section #1 #1](https://forum.wordreference.com/threads/important-please-read-before-you-post-الرجاء-القراءة-قبل-المشاركة.53282/)
let string = "انظر في قواميس WordReference (إذا كانت متوفرة) ثم اذهب إلى أدنى الصفحة حيث توجد قائمة بمواضيع المنتدى التي ناقشت الكلمة التى تبحث عنها، أو ابحث في المنتديات مباشرةً.​"
/// Raw attributed string produced from `string`
let attrString = NSAttributedString(string: string)
/// Expection: `string.count` should match `attrString.length`
print(string.count) // 165
print(attrString.length) // 166
print(attrString.string.count) // 165
/// Observation: iterating through the String.Index of `string`, we encounter
/// an "out of bounds" error, where we would expect a null index as a result of
/// the `limitedBy` parameter, directing the flow to line 28.
for i in 0..<200 {
if let parIndex = string.index(string.startIndex, offsetBy: i, limitedBy: string.endIndex) {
print("at index(\(i)): \(string[parIndex])")
} else {
print("no index: \(i)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment