-2

I have quick question about Swift algorithm, assuming I have a string “New Message” which option I need to use to get just initials NM ?

2

1 Answer 1

0

I would use map to get the first character of each word in the string, then use reduce to combine them.

let string = "New Message" let individualWords = string.components(separatedBy: " ") let firstCharacters = individualWords.map { $0.prefix(1) }.reduce("", +) print("firstCharacters is \(firstCharacters)") 

Result:

firstCharacters is NM

Edit: Per @LeoDabus' comment, joined is more concise than reduce("", +), and does the same thing.

let firstCharacters = individualWords.map { $0.prefix(1) }.joined() 
Sign up to request clarification or add additional context in comments.

3 Comments

.reduce("", +) ?? Why not simply .joined() ?
@LeoDabus ah yeah that would be better
in the first approach you can get rid of the map when reducing your string .reduce("") { $0 + $1.prefix(1) }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.