-1

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]
    }
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
TJ Olsen
  • 323
  • 2
  • 15

2 Answers2

1

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 KeyPaths:

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 }
TylerP
  • 9,600
  • 4
  • 39
  • 43
  • 1
    There is no need to use a closure `compactMap(\.serviceType)` you can use the KeyPath – Leo Dabus May 20 '20 at 02:07
  • 1
    Thanks @LeoDabus, I had no idea you could use keypaths like that as of Swift 5.2. I'll update my answer to include that! – TylerP May 20 '20 at 02:13
  • You are welcome KeyPaths where introduced in Swift 4 – Leo Dabus May 20 '20 at 02:14
  • Yes but this functionality was not introduced until [Swift 5.2](https://github.com/apple/swift-evolution/blob/master/proposals/0249-key-path-literal-function-expressions.md). – TylerP May 20 '20 at 02:14
  • Yes the use with compactMap was added later – Leo Dabus May 20 '20 at 02:16
  • 1
    https://stackoverflow.com/a/32021850/2303865 you can use it with split method as well but you need to disambiguate including the parameter name – Leo Dabus May 20 '20 at 02:24
1

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

Craig Temple
  • 525
  • 4
  • 10