Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value of character using ascii value in swift

Tags:

swift

ascii

I'm trying to change a string by changing each individual character.

Right now what I'm doing is reading through the string one character at a time, trying to convert it to ascii, and adding one to the value. I have the following code.

  var phrase = textfield1.text
    var i = 0
    for character in phrase
    {
        var s = String(character).unicodeScalars
        s[s.startIndex].value
        println(s[s.startIndex].value)
       if(i == 0)
        {
            s[s.startIndex].value += 1
        }
        if(i == 1)
        {
            s = s + 2
            i = 0
        }
    }

My println prints out the correct values for whatever words I enter, however I then am unable to manipulate it in my if statement. When I try it gives the following error:

Could not find member 'value'

Is it even possible to do what I'm trying?

like image 525
AndyReifman Avatar asked Dec 09 '22 05:12

AndyReifman


2 Answers

You're getting that error because the value property of a UnicodeScalar is read-only, but you're attempting to increment it.

Note that changing things in your loop won't have any effect on phrase - here's a way to do what you're doing using map():

let advanced = String(map(phrase) {
    (ch: Character) -> Character in
    switch ch {
    case " "..."}":                                  // only work with printable low-ASCII
        let scalars = String(ch).unicodeScalars      // unicode scalar(s) of the character
        let val = scalars[scalars.startIndex].value  // value of the unicode scalar
        return Character(UnicodeScalar(val + 1))     // return an incremented character
    default:
        return ch     // non-printable or non-ASCII
    }
})
like image 60
Nate Cook Avatar answered Dec 11 '22 07:12

Nate Cook


The unicodeScalars property is readonly, so you cannot modify it directly.

What you can do is to build a new string from the (modified) Unicode scalars:

var text = "HELLO 🇩🇪 !"
var newText = ""

for uni in text.unicodeScalars {
    var val = uni.value
    if val >= 0x41 && val < 0x5A { // If in the range "A"..."Y", just as an example
        val += 1 // or whatever ...
    }
    newText.append(UnicodeScalar(val))
}

println(newText) // "IFMMP 🇩🇪 !"

But note that val is a Unicode value, not an ASCII code. You might want to add a check if val is in the range of alphanumeric characters or similar before modifying it.


Update for Swift 3: (Thanks to @adrian.)

let text = "HELLO 🇩🇪 !"
var newText = ""

for uni in text.unicodeScalars {
    var val = uni.value
    if val >= 0x41 && val < 0x5A { // If in the range "A"..."Y", just as an example
        val += 1 // or whatever ...
    }
    newText.append(Character(UnicodeScalar(val)!))
}

print(newText) // "IFMMP 🇩🇪 !"
like image 31
Martin R Avatar answered Dec 11 '22 08:12

Martin R