Created
May 5, 2016 14:02
-
-
Save hishma/3b97384f76a183fbc3203577ae68fe5a to your computer and use it in GitHub Desktop.
Swift extension to NSPersonNameComponents for Prince & friends.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} | |
} |
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
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.