Changing character value using ascii value in swift
I am trying to change a string by changing every single character.
Right now, what I am doing is I am reading line by line one character at a time, trying to convert it to ascii and appending it 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 outputs the correct values ββfor any words I enter, however I cannot manipulate it in the if statement. When I try it gives the following error:
Could not find member 'value'
Can you even do what I am trying to do?
source to share
You are getting this error because the property value
for UnicodeScalar
is read-only, but you are trying to increase it.
Note that changing the elements in your loop will not affect phrase
- here's a way to do what you are 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
}
})
source to share
The property unicodeScalars
is read-only, so you cannot change it directly.
What you can do is construct a new string from (modified) Unicode scanners:
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 this val
is a Unicode value, not an ASCII code. You might want to add a check if it val
is in the range of alphanumeric characters or similar data prior to modifying it.
Update for Swift 3: (Thanks @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 π©πͺ !"
source to share