我只是想从名称字符串中获取姓氏的名字和名字的首字母,即,如果名称是“ John Paul Apple”,我希望abbvName是JohnA。
是否有比下面的代码更优雅的方法……我尝试使用reduce却无法正常工作
// 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
我尝试了reduce,但是只能按照this的帖子给它起首字母
let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }