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

前端 未结 6 1973
旧巷少年郎
旧巷少年郎 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条回答
  •  猫巷女王i
    2020-12-01 10:50

    To perform string operation based on index , you can not do it with traditional index numeric approach. because swift.index is retrieved by the indices function and it is not in the Int type. Even though String is an array of characters, still we can't read element by index.

    This is frustrating.

    So ,to create new substring of every even character of string , check below code.

    let mystr = "abcdefghijklmnopqrstuvwxyz"
    let mystrArray = Array(mystr)
    let strLength = mystrArray.count
    var resultStrArray : [Character] = []
    var i = 0
    while i < strLength {
        if i % 2 == 0 {
            resultStrArray.append(mystrArray[i])
          }
        i += 1
    }
    let resultString = String(resultStrArray)
    print(resultString)
    

    Output : acegikmoqsuwy

    Thanks In advance

提交回复
热议问题