Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Swift Character to String?

Tags:

I want to return the first letter of a String as a String instead of as a Character:

func firstLetter() -> String {     return self.title[0] } 

However, with the above I get Character is not convertible to String. What's the right way to convert a Character to a String?

This answer suggests creating a subscript extension, but the declaration for String already has a subscript method:

subscript (i: String.Index) -> Character { get } 

Is that answer outdated, or are these two different things?

like image 388
Snowman Avatar asked Jul 31 '14 14:07

Snowman


People also ask

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.

How do I convert a character to lowercase in Swift?

Swift String lowercased() The lowercased() method converts all uppercase characters in a string into lowercase characters.

Is there a character type in Swift?

Swift CharacterCharacter is a data type that represents a single-character string ( "a" , "@" , "5" , etc). Here, the letter variable can only store single-character data.


2 Answers

Why don't you use String interpolation to convert the Character to a String?

return "\(firstChar)" 
like image 148
Sascha L. Avatar answered Oct 16 '22 20:10

Sascha L.


Just the first character? How about:

var str = "This is a test" var result = str[str.startIndex..<str.startIndex.successor()] // "T": String 

Returns a String (as you'd expect with a range subscript of a String) and works as long as there's at least one character.

This is a little shorter, and presumably might be a fraction faster, but to my mind doesn't read quite so clearly:

var result = str[str.startIndex...str.startIndex] 
like image 43
Matt Gibson Avatar answered Oct 16 '22 19:10

Matt Gibson