Reputation: 4332
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
Reputation: 1751
Use prefix
For example:
let firstChar = firstMiddlename.prefix(1)
Upvotes: 1
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