Skip to content

Commit

Permalink
Swift 2 updates and post statuses
Browse files Browse the repository at this point in the history
  • Loading branch information
natecook1000 committed Sep 9, 2015
1 parent 1aca5ea commit 2b79390
Show file tree
Hide file tree
Showing 139 changed files with 560 additions and 97 deletions.
24 changes: 22 additions & 2 deletions 2012-07-07-nsindexset.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,35 @@ title: NSIndexSet
author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "NSIndexSet (and its mutable counterpart, NSMutableIndexSet) is a sorted collection of unique unsigned integers. Think of it like an NSRange that supports non-contiguous series. It has wicked fast operations for finding indexes in ranges or set intersections, and comes with all of the convenience methods you'd expect in a Foundation collection class."
excerpt: "NSIndexSet (like its mutable counterpart, NSMutableIndexSet) is a sorted collection of unique unsigned integers. Think of it like an NSRange that supports non-contiguous series. It has wicked fast operations for finding indexes in ranges or set intersections, and comes with all of the convenience methods you'd expect in a Foundation collection class."
status:
swift: 2.0
reviewed: September 8, 2015
---

`NSIndexSet` (and its mutable counterpart, `NSMutableIndexSet`) is a sorted collection of unique unsigned integers. Think of it like an `NSRange` that supports non-contiguous series. It has wicked fast operations for finding indexes in ranges or set intersections, and comes with all of the convenience methods you'd expect in a Foundation collection class.
`NSIndexSet` (like its mutable counterpart, `NSMutableIndexSet`) is a sorted collection of unique unsigned integers. Think of it like an `NSRange` that supports non-contiguous series. It has wicked fast operations for finding indexes in ranges or set intersections, and comes with all of the convenience methods you'd expect in a Foundation collection class.

You'll find `NSIndexSet` used throughout the Foundation framework. Anytime a method gets multiple elements from a sorted collection, such as an array or a table view's data source, you can be sure that an `NSIndexSet` parameter will be somewhere in the mix.

If you look hard enough, you may start to find aspects of your data model that could be represented with `NSIndexSet`. For example AFNetworking uses an index set to represent HTTP response status codes: the user defines a set of "acceptable" codes (in the `2XX` range, by default), and the response is checked by using `containsIndex:`.

The Swift standard library includes `PermutationGenerator`, an often-overlooked type that dovetails nicely with `NSIndexSet`. `PermutationGenerator` wraps a collection and a sequence of indexes (sound familiar?) to allow easy iteration:

```swift
let streetscape = ["Ashmead", "Belmont", "Clifton", "Douglas", "Euclid", "Fairmont",
"Girard", "Harvard", "Irving", "Kenyon", "Lamont", "Monroe",
"Newton", "Otis", "Perry", "Quincy"]

let selectedIndices = NSMutableIndexSet(indexesInRange: NSRange(0...2))
selectedIndices.addIndex(5)
selectedIndices.addIndexesInRange(NSRange(11...13))

for street in PermutationGenerator(elements: streetscape, indices: selectedIndices) {
print(street)
}
// Ashmead, Belmont, Clifton, Fairmont, Monroe, Newton, Otis
```

Here are a few more ideas to get you thinking in terms of index sets:

- Have a list of user preferences, and want to store which ones are switched on or off? Use a single `NSIndexSet` in combination with an `enum` `typedef`.
Expand Down
22 changes: 22 additions & 0 deletions 2012-07-14-nscache.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "Poor NSCache, always being overshadowed by NSMutableDictionary. It's as if no one knew how it provides all of that garbage collection behavior that developers take great pains to re-implement themselves."
status:
swift: 2.0
reviewed: September 8, 2015
---

Poor `NSCache`, always being overshadowed by `NSMutableDictionary`. It's as if no one knew how it provides all of that garbage collection behavior that developers take great pains to re-implement themselves.
Expand Down Expand Up @@ -37,3 +40,22 @@ Read: don't use this method unless you work at Apple and know the original autho
There's also a whole part about controlling whether objects are automatically evicted with `evictsObjectsWithDiscardedContent` & `<NSDiscardableContent>`, but it will probably just cause you more problems.

Despite all of this, developers should be using `NSCache` a lot more than they currently are. Anything in your project that you call a "cache", but isn't `NSCache` would be prime candidates for replacement. But if you do, just be sure to stick to the classics: `objectForKey:`, `setObject:forKey:` & `removeObjectForKey:`.

Still not convinved? As a parting gift, we'll even make it easier, via a little subscripting majick:

```swift
extension NSCache {
subscript(key: AnyObject) -> AnyObject? {
get {
return objectForKey(key)
}
set {
if let value: AnyObject = newValue {
setObject(value, forKey: key)
} else {
removeObjectForKey(key)
}
}
}
}
```
2 changes: 2 additions & 0 deletions 2012-07-24-nssortdescriptor.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "Sorting: it's the mainstay of Computer Science 101 exams and whiteboarding interview questions. But when was the last time you actually needed to know how to implement Quicksort yourself?"
status:
swift: 1.1
---

Sorting: it's the mainstay of Computer Science 101 exams and whiteboarding interview questions. But when was the last time you actually needed to know how to implement Quicksort yourself?
Expand Down
2 changes: 2 additions & 0 deletions 2012-07-31-nsdatecomponents.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ title: NSDateComponents
author: Mattt Thompson
category: Cocoa
excerpt: "NSDateComponents serves an important role in Foundation's date and time APIs. By itself, it's nothing impressive—just a container for information about a date (its month, year, day of month, week of year, or whether that month is a leap month). However, combined with NSCalendar, NSDateComponents becomes a remarkably convenient interchange format for calendar calculations."
status:
swift: 1.1
---

`NSDateComponents` serves an important role in Foundation's date and time APIs. By itself, it's nothing impressive—just a container for information about a date (its month, year, day of month, week of year, or whether that month is a leap month). However, combined with `NSCalendar`, `NSDateComponents` becomes a remarkably convenient interchange format for calendar calculations.
Expand Down
2 changes: 2 additions & 0 deletions 2012-08-06-cfstringtransform.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster, popular
excerpt: "NSString is the crown jewel of Foundation. But as powerful as it is, one would be remiss not to mention its toll-free bridged cousin, CFMutableString—or more specifically, CFStringTransform."
status:
swift: 1.2
---

There are two indicators that tell you everything you need to know about how nice a language is to use:
Expand Down
3 changes: 3 additions & 0 deletions 2012-08-13-nsincrementalstore.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ title: NSIncrementalStore
author: Mattt Thompson
category: Cocoa
excerpt: Even for a blog dedicated to obscure APIs, `NSIncrementalStore` sets a new standard. It was introduced in iOS 5, with no more fanfare than the requisite entry in the SDK changelog. Ironically, it is arguably the most important thing to come out of iOS 5, which will completely change the way we build apps from here on out.
status:
swift: 1.1
reviewed: September 8, 2015
---

Even for a blog dedicated to obscure APIs, `NSIncrementalStore` brings a new meaning to the word "obscure".
Expand Down
2 changes: 2 additions & 0 deletions 2012-08-27-cfbag.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "In the pantheon of collection data types in computer science, bag doesn't really have the same clout as lists, sets, associative arrays, trees, graphs, or priority queues. In fact, it's pretty obscure. You've probably never heard of it."
status:
swift: t.b.c
---

Objective-C is a language caught between two worlds.
Expand Down
2 changes: 2 additions & 0 deletions 2012-09-03-nslocale.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "Internationalization is like flossing: everyone knows they should do it, but probably don't."
status:
swift: 1.1
---

Internationalization is like flossing: everyone knows they should do it, but probably don't.
Expand Down
2 changes: 2 additions & 0 deletions 2012-09-10-uiaccessibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "Accessibility, like internationalization, is one of those topics that's difficult to get developers excited about. But as you know, NSHipster is all about getting developers excited about this kind of stuff."
status:
swift: n/a
---

> We all want to help one another, human beings are like that.
Expand Down
2 changes: 2 additions & 0 deletions 2012-09-17-nscharacterset.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ title: NSCharacterSet
author: Mattt Thompson
category: Cocoa
excerpt: "Foundation boasts one of the best, most complete implementations of strings around. But a string implementation is only as good as the programmer who wields it. So this week, we're going to explore some common uses--and misuses--of an important part of the Foundation string ecosystem: NSCharacterSet."
status:
swift: 1.1
---

As mentioned [previously](http://nshipster.com/cfstringtransform/), Foundation boasts one of the best, most complete implementations of strings around.
Expand Down
2 changes: 2 additions & 0 deletions 2012-09-24-uicollectionview.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ title: UICollectionView
author: Mattt Thompson
category: Cocoa
excerpt: "UICollectionView single-handedly changes the way we will design and develop iOS apps from here on out. This is not to say that collection views are in any way unknown or obscure. But being an NSHipster isn't just about knowing obscure gems in the rough. Sometimes, it's about knowing about up-and-comers before they become popular and sell out."
status:
swift: 1.1
---

`UICollectionView` is the new `UITableView`. It's that important.
Expand Down
2 changes: 2 additions & 0 deletions 2012-10-01-pragma.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Objective-C
tags: nshipster
excerpt: "`#pragma` declarations are a mark of craftsmanship in Objective-C. Although originally purposed for compiling source code across many different compilers, the modern Xcode-savvy programmer uses #pragma declarations to very different ends."
status:
swift: n/a
---

`#pragma` declarations are a mark of craftsmanship in Objective-C. Although originally used to make source code compatible between different compilers, the Xcode-savvy coder uses `#pragma` declarations to very different ends.
Expand Down
2 changes: 2 additions & 0 deletions 2012-10-08-at-compiler-directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ author: Mattt Thompson
category: Objective-C
tags: nshipster
excerpt: "If we were to go code-watching for Objective-C, what would we look for? Square brackets, ridiculously-long method names, and `@`'s. \"at\" sign compiler directives are as central to understanding Objective-C's gestalt as its ancestry and underlying mechanisms. It's the sugary glue that allows Objective-C to be such a powerful, expressive language, and yet still compile all the way down to C."
status:
swift: n/a
---

Birdwatchers refer to it as (and I swear I'm not making this up) ["Jizz"](http://en.wikipedia.org/wiki/Jizz_%28birding%29): those indefinable characteristics unique to a particular kind of thing.
Expand Down
2 changes: 2 additions & 0 deletions 2012-10-15-addressbookui.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ title: AddressBookUI
author: Mattt Thompson
category: Cocoa
excerpt: "Address Book UI is an iOS framework for displaying, selecting, editing, and creating contacts in a user's Address Book. Similar to the Message UI framework, Address Book UI contains a number of controllers that can be presented modally, to provide common system functionality in a uniform interface."
status:
swift: 1.1
---

[Address Book UI](https://developer.apple.com/LIBRARY/ios/documentation/AddressBookUI/Reference/AddressBookUI_Framework/index.html) is an iOS framework for displaying, selecting, editing, and creating contacts in a user's Address Book. Similar to the [Message UI](https://developer.apple.com/library/IOs/documentation/MessageUI/Reference/MessageUI_Framework_Reference/index.html) framework, Address Book UI contains a number of controllers that can be presented modally, to provide common system functionality in a uniform interface.
Expand Down
22 changes: 19 additions & 3 deletions 2012-10-22-nslinguistictagger.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "NSLinguisticTagger is a veritable Swiss Army Knife of linguistic functionality, with the ability to tokenize natural language strings into words, determine their part-of-speech & stem, extract names of people, places, & organizations, and tell you the languages & respective writing system used in the string."
status:
swift: 2.0
reviewed: September 8, 2015
---

`NSLinguisticTagger` is a veritable Swiss Army Knife of linguistic functionality, with the ability to [tokenize](http://en.wikipedia.org/wiki/Tokenization) natural language strings into words, determine their part-of-speech & [stem](http://en.wikipedia.org/wiki/Word_stem), extract names of people, places, & organizations, and tell you the languages & respective [writing system](http://en.wikipedia.org/wiki/Writing_system) used in the string.
Expand All @@ -22,16 +25,15 @@ Computers are a long ways off from "understanding" this question literally, but

~~~{swift}
let question = "What is the weather in San Francisco?"
let options: NSLinguisticTaggerOptions = .OmitWhitespace | .OmitPunctuation | .JoinNames
let options: NSLinguisticTaggerOptions = [.OmitWhitespace, .OmitPunctuation, .JoinNames]
let schemes = NSLinguisticTagger.availableTagSchemesForLanguage("en")
let tagger = NSLinguisticTagger(tagSchemes: schemes, options: Int(options.rawValue))
tagger.string = question
tagger.enumerateTagsInRange(NSMakeRange(0, (question as NSString).length), scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass, options: options) { (tag, tokenRange, sentenceRange, _) in
tagger.enumerateTagsInRange(NSMakeRange(0, (question as NSString).length), scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass, options: options) { (tag, tokenRange, _, _) in
let token = (question as NSString).substringWithRange(tokenRange)
println("\(token): \(tag)")
}
~~~

~~~{objective-c}
NSString *question = @"What is the weather in San Francisco?";
NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
Expand Down Expand Up @@ -153,6 +155,20 @@ By default, each token in a name is treated as separate instances. In many circu

---

Finally, NSString provides convenience methods that handle the setup and configuration of NSLinguisticTagger on your behalf. For one-off tokenizing, you can save a lot of boilerplate:

```swift
var tokenRanges: NSArray?
let tags = "Where in the world is Carmen San Diego?".linguisticTagsInRange(
NSMakeRange(0, (question as NSString).length),
scheme: NSLinguisticTagSchemeNameTypeOrLexicalClass,
options: options, orthography: nil, tokenRanges: &tokenRanges
)
// tags: ["Pronoun", "Preposition", "Determiner", "Noun", "Verb", "PersonalName"]
```

---

Natural language is woefully under-utilized in user interface design on mobile devices. When implemented effectively, a single utterance from the user can achieve the equivalent of a handful of touch interactions, in a fraction of the time.

Sure, it's not easy, but if we spent a fraction of the time we use to make our visual interfaces pixel-perfect, we could completely re-imagine how users best interact with apps and devices. And with `NSLinguisticTagger`, it's never been easier to get started.
23 changes: 12 additions & 11 deletions 2012-10-29-uilocalizedindexedcollation.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ author: Mattt Thompson
category: Cocoa
tags: nshipster
excerpt: "UITableView starts to become unwieldy once it gets to a few hundred rows. If users are reduced to frantically scratching at the screen like a cat playing Fruit Ninja in order to get at what they want... you may want to rethink your UI approach."
status:
swift: 2.0
reviewed: September 8, 2015
---

UITableView starts to become unwieldy once it gets to a few hundred rows. If users are reduced to frantically scratching at the screen like a [cat playing Fruit Ninja](http://www.youtube.com/watch?v=CdEBgZ5Y46U) in order to get at what they want... you may want to rethink your UI approach.
Expand Down Expand Up @@ -60,16 +63,14 @@ All told, here's what a typical table view data source implementation looks like

~~~{swift}
class ObjectTableViewController: UITableViewController {
let collation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
var sections: [[Object]] = []
var objects: [Object] {
let collation = UILocalizedIndexedCollation.currentCollation()
var sections: [[AnyObject]] = []
var objects: [AnyObject] = [] {
didSet {
let selector: Selector = "localizedTitle"
sections = Array(count: collation.sectionTitles.count, repeatedValue: [])
sections = [[Object]](count: collation.sectionTitles.count, repeatedValue: [])
let sortedObjects = collation.sortedArrayFromArray(objects, collationStringSelector: selector) as [Object]
let sortedObjects = collation.sortedArrayFromArray(objects, collationStringSelector: selector)
for object in sortedObjects {
let sectionNumber = collation.sectionForObject(object, collationStringSelector: selector)
sections[sectionNumber].append(object)
Expand All @@ -81,15 +82,15 @@ class ObjectTableViewController: UITableViewController {
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
return collation.sectionTitles![section] as String
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String {
return collation.sectionTitles[section]
}
override func sectionIndexTitlesForTableView(tableView: UITableView!) -> [AnyObject]! {
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String] {
return collation.sectionIndexTitles
}
override func tableView(tableView: UITableView!, sectionForSectionIndexTitle title: String!, atIndex index: Int) -> Int {
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return collation.sectionForSectionIndexTitleAtIndex(index)
}
}
Expand Down
2 changes: 2 additions & 0 deletions 2012-11-05-nsurlprotocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ title: NSURLProtocol
author: Mattt Thompson
category: Cocoa
excerpt: "Foundation’s URL Loading System is something that every iOS developer would do well to buddy up with. And of all of networking classes and protocols of Foundation, NSURLProtocol is perhaps the most obscure and powerful."
status:
swift: n/a
---

iOS is all about networking--whether it's reading or writing state to and from the server, offloading computation to a distributed system, or loading remote images, audio, and video from the cloud.
Expand Down
Loading

0 comments on commit 2b79390

Please sign in to comment.