30

Let's assume this situation: I have an array of objects and I want call instance method on each one of them. I can do something like that:

//items is an array of objects with instanceMethod() available
items.forEach { $0.instanceMethod() }

The same situation is with map. For example I want to map each object to something else with mappingInstanceMethod which returns value:

let mappedItems = items.map { $0.mappingInstanceMethod() }

Is there a cleaner way to do that?

For example in Java one can do:

items.forEach(Item::instanceMethod);

instead of

items.forEach((item) -> { item.instanceMethod(); });

Is similiar syntax available in Swift?

0

3 Answers 3

55

What you are doing in

items.forEach { $0.instanceMethod() }
let mappedItems = items.map { $0.mappingInstanceMethod() }

is a clean and Swifty way. As explained in Is there a way to reference instance function when calling SequenceType.forEach?, the first statement cannot be reduced to

items.forEach(Item.instanceMethod)

There is one exception though: It works with init methods which take a single argument. Example:

let ints = [1, 2, 3]
let strings = ints.map(String.init)
print(strings) // ["1", "2", "3"]
3
    for item in items {
        item.instanceMethod()
    }
3
  • Ok, maybe I should have been more specific. I want closure syntax which can be also used in map function for example. Dec 14, 2015 at 13:42
  • 3
    Question is, why would you prefer a closure syntax. Closures are great, and very handy at times - but there's a price to pay. In debugging - they are "unnamed" and hard to trace-back. Only use them when you want to, say, receive a closure from the outside (as input to your function) and apply it to each element, things like that. For simpler scenarios - use simpler semantics. It'll also help the readers of your code. Jul 15, 2018 at 8:46
  • What if instanceMethod is a mutating function in struct?
    – Satyam
    Nov 14, 2020 at 4:56
2

have you tried

let mappedItems = items.map { $0.mappingInstanceMethod() }

note the () to call the method

Edit 1:

sample code:

class SomeObject {

    func someFunction() -> Int {
        return 5
    }
}

let array = [SomeObject(), SomeObject(), SomeObject()]

let ints = array.map { $0.someFunction()}
print(ints)
2
  • It was just a typo, I fixed it. Dec 14, 2015 at 14:19
  • I know that it works, I was just looking for other syntax for this. As @MartinR pointed out in his comments, this is the 'swiftiest' way to do this and there is no shorter way available. Dec 14, 2015 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.