Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Converting Character to String

Tags:

ios

swift

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

like image 405
Antiokhos Avatar asked Aug 03 '14 16:08

Antiokhos


People also ask

How do you convert something to a string in Swift?

To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.

How do I convert a string to a character in Swift?

this should be as simple as let characterFromString = Character(textField. text) . NSString is automatically bridged to Swift's String , and the Character class has an init which accepts a single character String ; see the documentation here.

What is CharacterSet in Swift?

Overview. A CharacterSet represents a set of Unicode-compliant characters. Foundation types use CharacterSet to group characters together for searching operations, so that they can find any of a particular set of characters during a search.

What is string element in Swift?

Element. A type representing the sequence's elements.


1 Answers

How about the simple String(theCharacter)

Works in Swift 4 and Swift 5

like image 145
Naishta Avatar answered Sep 16 '22 17:09

Naishta