MilkBottle
MilkBottle

Reputation: 4332

How to get the first character from a word or a string

Say , I have the middlename as follows and I used below code.

var firstMiddlename = "Thompson"

let firstCharIndex = firstMiddlename.startIndex

let firstChar = firstMiddlename.index(after: firstCharIndex)

Somehow, this is not working. Please show me how to get the first character.

// update:

var firstMiddlename = "Thompson"

let firstCharacter = firstMiddlename.first

let name = MyFirstName + " " + firstCharacter + " " + MyLastName

Error:

Binary operator '+' cannot be applied to operands of type 'String' and 'Character?'

Thanks

Upvotes: 0

Views: 56

Answers (2)

Element Zero
Element Zero

Reputation: 1751

Use prefix

For example:

let firstChar = firstMiddlename.prefix(1)

Upvotes: 1

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

Swift 4.x

var firstMiddlename = "Thompson"

let firstCharcter = firstMiddlename.first

print(firstCharcter) // T

And if you want to set of character from first or last. You can use prefix

firstMiddlename.prefix(2) // Th

And final append string like this

let name = "\(MyLastName) \(firstMiddlename.first!) \(MyLastName)"

Upvotes: 1

Related Questions