There's no need to avoid Swift Array
.
It's bridged in both directions with NSArray
, so for more type-safe code it's best to do your work with Swift arrays and bridge only when needed for interoperating with ObjC APIs. (And in most imported APIs, Swift automatically converts NSArray
to [AnyObject]
, so you don't even need to bridge very often.)
Assuming the persons
array is an [AnyObject]
you got from other API, you can cut down on the amount of type casting relative to other answers by casting the array first:
let sortedPersons = sorted(persons as [Person]) { $0.name < $1.name }
// sortedPersons has inferred type [Person]
Also, since you're using a comparator block only to sort on a specific property of your Person
class, you might do better to use sort descriptors:
let sortedPersons = (persons as NSArray).sortedArrayUsingDescriptors([
NSSortDescriptor(key: "name", ascending: true)
])
(The persons as NSArray
part may not be necessary if persons
came from an ObjC API.)
Depending on how the Person
class is implemented, sorting with descriptors can produce a more efficient sort on the backend. For example, if it's a Core Data managed object, sorting with descriptors might produce a SQL query that executes fast in the database and uses little memory, while sorting with a comparator closure requires instantiating every object from the database just to evaluate the closure against each.