SwiftUI Array methods

up:: SwiftUI onboarding

Source: Sort, Filter, and Map data arrays in Swift | Continued Learning #13

Sort

let sortedArray = dataArray.sorted { (user1, user2) -> Bool in {
		return user1.points > user2.points
	}
}
 
// shorthand
let sortedShortArray = dataArray.sorted(by: { $0.points > $1.points })

Filter

let filteredArray = dataArray.filter({ (user) -> Bool in {
		return user.points > 50
	} 
})
 
// shorthand
let filteredShortArray = dataArray.filter({ $0.points > 50 })

Map

Convert from one type to another.

let mappedArray = dataArray.map({ (user) -> String in
	return user.name
})
 
// shorthand
let mappedShortArray = dataArray.map({ $0.name })

CompactMap

For optional properties. If user.name = nil, it just won’t be included.

let mappedArray = dataArray.compactMap({ (user) -> String? in
	return user.name
})
 
// shorthand
let mappedShortArray = dataArray.compactMap({ $0.name })