Snowman
Snowman

Reputation: 32091

How to convert Swift Character to String?

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?

Upvotes: 22

Views: 22800

Answers (9)

nCod3d
nCod3d

Reputation: 687

As of Swift 2.3/3.0+ you can do something like this:

func firstLetter() -> String {
    guard let firstChar = self.title.characters.first else {
        return ""  // If title is nil return empty string
    }
    return String(firstChar)
}

Or if you're OK with optional String:

func firstLetter() -> String? {
    guard let firstChar = self.title.characters.first else {
       return nil
    }
    return String(firstChar)
}

Update for Swift 4, also think an extension is better

extension String{
func firstLetter() -> String {
    guard let firstChar = self.first else {
        return ""
    }
    return String(firstChar)
}

Upvotes: 6

ChopinBrain
ChopinBrain

Reputation: 121

I was trying to get single characters from a parsed String into a String. So I wanted B from helpAnswer in String format not CHARACTER format, so I could print out the individual characters in a text box. This works great. I don't know about the efficiency of it. But it works. SWIFT 3.0
Thanks for everyones help.....

var helpAnswer = "ABC"
var String1 = ""
var String2 = ""
var String3 = ""


 String1 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 0)]))
 String2 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 1)]))
 String3 = (String(helpAnswer[helpAnswer.index(helpAnswer.startIndex, offsetBy: 1)])

Upvotes: 0

Warif Akhand Rishi
Warif Akhand Rishi

Reputation: 24248

let str = "My String"
let firstChar = String(str.characters.first!)

Upvotes: 0

Sascha L.
Sascha L.

Reputation: 357

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

return "\(firstChar)"

Upvotes: 27

Matt Gibson
Matt Gibson

Reputation: 38238

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]

Upvotes: 9

hnh
hnh

Reputation: 14815

First: The answer you refer to is still relevant. It adds Integer based indices to String (e.g. using advance()). The builtin String subscript only supports BidirectionalIndices (think of them more like cursors, not as array-indices). This is likely because the Characters are not usually stored as such in the String structure, but as UTF-8 or UTF-16. Positional access to the characters then requires decoding (which is why - in addition to the extra copying - Array(string)[idx] is really expensive).

If you really just want the first char, you could do this:

extension String {
  var firstCharacterAsString : String {
    return self.startIndex == self.endIndex
      ? ""
      : String(self[self.startIndex])
  }
}

Upvotes: -1

NRitH
NRitH

Reputation: 13903

The simplest way is return "\(self.title[0])".

Upvotes: -2

P1kachu
P1kachu

Reputation: 1077

I did some researches for the same type of question, and I found this way to get any character from any string:

func charAsString(str:String, index:Int) -> String {
    return String(Array(str)[index])
}

and for the first character you call

var firstCharAsString = firstLetter("yourString",0)

I am a not very good at programming yet but I think that this will do what you want

EDIT:

Simplified for your need:

func firstChar(str:String) -> String {
    return String(Array(str)[0])
}

I hope that it's what you need

Upvotes: 3

Coder404
Coder404

Reputation: 742

This is what I would do:

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

Upvotes: -1

Related Questions