Skip to content

Instantly share code, notes, and snippets.

@hishma
Created May 5, 2016 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishma/3b97384f76a183fbc3203577ae68fe5a to your computer and use it in GitHub Desktop.
Save hishma/3b97384f76a183fbc3203577ae68fe5a to your computer and use it in GitHub Desktop.
Swift extension to NSPersonNameComponents for Prince & friends.
//
// NSPersonNameComponents.swift
//
import Foundation
extension NSPersonNameComponents {
// Because the web is generally xenophobic…
var xenophobicName: (firstName: String, lastName: String)? {
let firstName: String? = ((givenName ?? "").isEmpty ? nil : givenName!)
let lastName: String? = ((familyName ?? "").isEmpty ? nil : familyName!)
switch (firstName, lastName) {
case let (first, last) where first != nil && last != nil:
return (first!, last!)
case let (first, last) where first != nil && last == nil:
return (first!, first!)
case let (first, last) where first == nil && last != nil:
return (last!, last!)
default:
return nil
}
}
}
@hishma
Copy link
Author

hishma commented May 5, 2016

Because in my experience most web service API's that have been exposed on an existing web app, tend to require a first and last name, even though a lot of the world's names don't fit that mold. And you probably really don't need anything more than a simple name field in a lot of cases.

This can be problematic when interacting with API's in cases where providing UI that mimics traditional web form validation may not be pragmatic or desirable. That was the case for me when implementing Apple Pay support, where the system provides its own UI and access the users contact information directly. Plus in that case the whole point is to let folks pay using the data they already have without additional interaction.

Apple's documentation for the NSPersonNameComponents does a pretty nice job of explaining the subtle complexities involved with names.

Also, the book Design for Real Life by Eric Meyer & Sara Wachter-Boettcher from A Book Apart goes into even more details, along with related topics.

@hishma
Copy link
Author

hishma commented May 5, 2016

Pseudo code-ish table of results:

givenName familyName result
Prince Nelson (firstName: "Prince", lastName: "Nelson")
Prince nil (firstName: "Prince", lastName: "Prince")
Prince "" (firstName: "Prince", lastName: "Prince")
nil Nelson (firstName: "Nelson", lastName: "Nelson")
"" Nelson (firstName: "Nelson", lastName: "Nelson")
nil nil nil
"" "" nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment