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?
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.
Swift String lowercased() The lowercased() method converts all uppercase characters in a string into lowercase characters.
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.
Why don't you use String interpolation to convert the Character to a String?
return "\(firstChar)"
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With