Swift Documentation: Life Pro Tips

Swift Life Pro Tip: If you’re working with a Swiftized version of what was originally a Cocoa /Touch Foundation type, always check the header file just in case there’s more info that’s missing from the Swift version.

To take an example from a conversation today, consider the following code. What happens if you pass nil rather than an actual locale?

let string = "istanbul"
print(string.uppercased()) // ISTANBUL

import Foundation
let locale = Locale(identifier: "tr")
print(string.uppercased(with: locale)) 
// İSTANBUL, with the dot over the I

print(string.uppercased(with: nil))  // ??

Swift

Cocoa/Touch Foundation

Looking up Headers

The header files use traditional comments that I assume aren’t picked up by automatic document generation:

  1. Look up declaration for the NS version of a Swift Foundation class, such as NSString vs String.
  2. Click Objective-C and away from Swift.
  3. De-swiftize the `uppercase(with:)` declaration. In this case, the ObjC declaration is, `- (NSString *)uppercaseStringWithLocale:(NSLocale *)locale;`
  4. Find the header file (I have System/Library/Framework on perma-symbolic link from my home folder) and look there for NSString.h.
  5. Look at the original declaration in the header file:
/* The following methods perform localized case mappings based on the locale specified. Passing nil indicates the canonical mapping. For the user preference locale setting, specify +[NSLocale currentLocale].
*/

Hope this helps someone.

Tangentially, Zev Eisenberg reminds me to link to the Swift String Manifesto, which addresses a bit of this issue.

Got other Swift Life Pro Tips? Drop a comment, a tweet, or an email. Thanks!

Comments are closed.