How to convert “Index” to type “Int” in Swift?

前端 未结 6 1960
旧巷少年郎
旧巷少年郎 2020-12-01 10:19

I want to convert the index of a letter contained within a string to an integer value. Attempted to read the header files but I cannot find the type for Index,

6条回答
  •  借酒劲吻你
    2020-12-01 10:42

    encodedOffset has deprecated from Swift 4.2.

    Deprecation message: encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.

    So we can use utf16Offset(in:) like this:

    var str = "abcdefgc"
    let index = str.index(of: "c")?.utf16Offset(in: str) // Result: 2
    

提交回复
热议问题