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

前端 未结 6 1961
旧巷少年郎
旧巷少年郎 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:43

    Swift 4

    var str = "abcdefg"
    let index = str.index(of: "c")?.encodedOffset // Result: 2
    

    Note: If String contains same multiple characters, it will just get the nearest one from left

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

提交回复
热议问题