[swift-users] UTF-16 string index can be incremented beyond end index

Martin R martinr448 at gmail.com
Thu Mar 16 15:00:33 CDT 2017


The index of the UTF-16 view of a string can be incremented beyond the end index:

    let s = "foo"

    let u16 = s.utf16
    let i16 = u16.index(u16.endIndex, offsetBy: 99, limitedBy: u16.endIndex)

    print(i16 as Any)
    // Optional(Swift.String.UTF16View.Index(_offset: 102))

I wonder if this behaviour is intended or if I should file a bug report.

All other string views behave as I would expect it:

    let cs = s.characters
    let ic = cs.index(cs.endIndex, offsetBy: 99, limitedBy: cs.endIndex)
    print(ic as Any) // nil

    let u8 = s.utf8
    let i8 = u8.index(u8.endIndex, offsetBy: 99, limitedBy: u8.endIndex)
    print(i8 as Any) // nil

    let us = s.unicodeScalars
    let iu = us.index(us.endIndex, offsetBy: 99, limitedBy: us.endIndex)
    print(iu as Any) // nil

Tested with Xcode 8.2.1 and 8.3 beta 4.

Regards, Martin



More information about the swift-users mailing list