Is there a short hand way of doing something like this in Swift?
var serviceTypes = [String]()
for menu in menus {
if let serviceType = menu.serviceType {
serviceTypes += [serviceType]
}
}
In your case, since you're only adding to the other array if the serviceType
is non-nil, use compactMap(_:)
.
If you're using Swift 5.2 or later, you can do this with KeyPath
s:
let serviceTypes = menus.compactMap(\.serviceType)
If you're using a version of Swift prior to 5.2, you can use a closure:
let serviceTypes = menus.compactMap { $0.serviceType }
map()
is your friend! (And it has friends, flatMap()
and compactMap()
.)
var serviceTypes = menus.compactMap {$0.serviceType}
More info here: https://www.hackingwithswift.com/articles/205/whats-the-difference-between-map-flatmap-and-compactmap