0

I simply want to get the first name and first initial of the last name from a name string ie if name is "John Paul Apple" I want the abbvName to be JohnA.

Is there a more elegant way to do this than the following code ... I tried with reduce but couldn't get it to work

// get first name & last name initial
let name = "John Paul Apple"
let nameComponents = name.components(separatedBy: " ")
guard let firstname  = nameComponents.first, !firstname.isEmpty else { return }
guard let lastname = nameComponents.last, !lastname.isEmpty else { return }
let startIx = lastname.startIndex
let lastinit = String(lastname.first!)
let abbvName = firstname + lastinit

I tried reduce ie but can only get it giving me initials as per this post

let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
lozflan
  • 835
  • 10
  • 23
  • You're making lots of [incorrect assumptions about names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) that could very likely lead you to some very frustrating operational burdens when customers interact with your system. I suggest you address these in your initial. design – Alexander Sep 18 '18 at 00:55
  • This is a much more complex problem then perhaps you expect. I very strongly recommend you delegate a task like this to a tried and true library that has done it correctly. I would recommend you look into employing [PersonNameComponentsFormatter](https://developer.apple.com/documentation/foundation/personnamecomponentsformatter) – Alexander Sep 18 '18 at 00:56
  • @Alexander I was going to recommend PersonNameComponentsFormatter as well but for some reason (with Xcode 10), I get "John Paul" as the `givenName` and no `middleName`. Seems like a bug. – rmaddy Sep 18 '18 at 01:15
  • @rmaddy not a bug John Paul it is considered a compound name if you change Paul to something else than typical given names it will be ignored – Leo Dabus Sep 18 '18 at 01:40
  • I had a look at PersonNameComponents and under the section titled "Short" it says "If a user has enabled the use of short names, the user can choose from one of four variations" ... Given Name - Family Initial Family Name - Given Initial Given Name Only Family Name Only ...although this appears to have the functionality I want, because it's dependant on the user allowing it, i didn't think it would suit what i was trying to do – lozflan Sep 18 '18 at 03:39

0 Answers0