Get the initials from a name and limit it to 2 initials

If you target iOS 9 and above:

let formatter = PersonNameComponentsFormatter()
if let components = formatter.personNameComponents(from: name) {
     formatter.style = .abbreviated
     return formatter.string(from: components)
}

This is my solution.

Swift 5

extension String {
    var initials: String {
        return self.components(separatedBy: " ")
            .reduce("") {
                ($0.isEmpty ? "" : "\($0.first?.uppercased() ?? "")") +
                ($1.isEmpty ? "" : "\($1.first?.uppercased() ?? "")")
            }
    }
}

Swift 4, little bit of extra work, but using PersonNameComponentsFormatter.

// Note: We Account for name suffix ( Example: III, II, Jr, Sr ) or prefixes ( Mr, Mrs )

let fullName = “Mr John Jacob Smith III”

let formatter = PersonNameComponentsFormatter()

guard let personNameComponents = formatter.personNameComponents(from: fullName) else {
  return ""
}

return personNameComponents.initials

// Note: Also create Extension for PersonNameComponents

// PersonNameComponents+Initials.swift

import Foundation

extension PersonNameComponents {
  var fullName: String {
    return [givenName, middleName, familyName].compactMap{ $0 }.joined(separator: " ")
  }

  var fullNameWithSuffix: String {
    return [givenName, middleName, familyName, nameSuffix].compactMap{ $0 }.joined(separator: " ")
  }

  var initials: String {
    let firstName = givenName?.first ?? Character(" ")
    let lastName = familyName?.first ?? Character(" ")
    return "\(firstName)\(lastName)".trimmingCharacters(in: .whitespaces)
  }

  // Note: If You need first, middle, last
  /*
  var initials: String {
    let firstName = givenName?.first ?? Character(" ")
    let middleName = middleName?.first ?? Character(" ")
    let lastName = familyName?.first ?? Character(" ")
    return "\(firstName)\(middleName)\(lastName)".trimmingCharacters(in: .whitespaces)
  }
  */
}

Swift 2.0

How about this:

let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.reduce("") { ($0 == "" ? "" : $0.first) + $1.first}

That will also take care of the case where the name has no middle name or more than 1 middle name.

Swift 3

let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.characters.first!)") + "\($1.characters.first!)" }

Swift 4

let initials = "John Fitzgerald Kennedy".components(separatedBy: " ").reduce("") { ($0 == "" ? "" : "\($0.first!)") + "\($1.first!)" }

Tags:

Ios

Swift