Swift Converting Character to String
Asked Answered
I

4

62

I have an issue with converting character type to String type. First of all, I have below extension of String for finding nth character within String.

extension String {
    func characterAtIndex(index: Int) -> Character? {
        var cur = 0
        for char in self {
            if cur == index {
                return char
            }
            cur++
        }
        return nil
    }
}

I get what I want with this class extension. However when I use that nth character for title of my custom UIButton, gives an error. My Uibutton Class is

class hareketliHarfler: UIButton {
    init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
    }
    func getLetter(letter:String!){
        self.titleLabel.text = letter 
    }
}

The error show when i try to access "getLetter(letter:String)" function. Here is example of main view Controller codes:

    var harfim = hareketliHarfler(frame: CGRectMake(100,100,100,100))
var str="This is my String"
var bufi=str.characterAtIndex(3)
    harfim.getLetter(bufi as AnyObject) ****

In * section I try .getLetter(bufi), .getLetter(bufi as String) also I try to change parameter type of function. Look like: func getLetter(letter:Character!) or func getLetter(letter:AnyObject!)...etc Didn't find a way. Need a help on that. Thank you

Instructor answered 3/8, 2014 at 16:15 Comment(2)
Please don't subvert the Swift String and Character types with "C" like tricks. There are methods in Swift to handle these things correctly and by that I mean all unicode characters.Tyburn
When asking about an error message, it's really helpful to post the text of the error message.Nasturtium
N
61

Your problem is quite simple: your characterAtIndex function returns a Character, and self.titleLabel.text is a String. You can't convert between the two implicitly. The easiest way would be to turn the Character into a String using the String initialiser:

// ch will be Character? type.
if let ch = str.characterAtIndex(3) {
    // Initialise a new String containing the single character 'ch'
    harfim.getLetter(String(ch))
} else {
    // str didn't have a third character.
}

Unlike other solutions, this is safe for unusual Unicode characters, and won't initialise a potentially large array or iterate the whole String just to get the third character.

Nasturtium answered 4/8, 2014 at 8:45 Comment(0)
P
80

How about the simple String(theCharacter)

Works in Swift 4 and Swift 5

Proposition answered 20/10, 2017 at 9:11 Comment(0)
N
61

Your problem is quite simple: your characterAtIndex function returns a Character, and self.titleLabel.text is a String. You can't convert between the two implicitly. The easiest way would be to turn the Character into a String using the String initialiser:

// ch will be Character? type.
if let ch = str.characterAtIndex(3) {
    // Initialise a new String containing the single character 'ch'
    harfim.getLetter(String(ch))
} else {
    // str didn't have a third character.
}

Unlike other solutions, this is safe for unusual Unicode characters, and won't initialise a potentially large array or iterate the whole String just to get the third character.

Nasturtium answered 4/8, 2014 at 8:45 Comment(0)
A
2

Change this:

var bufi=str.characterAtIndex(3)
harfim.getLetter(bufi as AnyObject)

to this:

harfim.getLetter(String(Array(str)[3]))

So what happening here:

  1. we create an array from our string. Array elements are symbols from original string. Such break down correctly tracks symbols that are presented with a sequences of two or more code points. E.g. emoji or flag as noted by @MartinR.

  2. We access element at 4-th position.

Note that as we crate an array from initial string then performance wise is better to use this method only with short strings and avoid it in oft-repeated routines. But in your case it seems to be OK.

Aguiar answered 3/8, 2014 at 16:42 Comment(1)
Since at least Beta 4 converting a String to an Array correctly handles utf characters that are composed of multiple utf-16 components.Tyburn
E
0

Can also use Character(text).isNumber if you want to get localised numbers.

Reference: https://developer.apple.com/documentation/swift/character/3127015-isnumber

Ezekielezell answered 24/9, 2019 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.