Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling instance method on each object in array

Tags:

swift

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?

like image 565
Sebastian Osiński Avatar asked Dec 14 '15 13:12

Sebastian Osiński


People also ask

How do you call methods in an array of objects?

If you really have to use an array of Object, and call a getSalary() method, you will have to cast the array elements to the class or interface to which the method getSalary() belongs. For example and again, if this class is called Employee : Employee employee = (Employee) array[i]; employee. getSalary();

How do you call a method using an array of objects in Java?

public static void main(String[] args) { Object[] type = new Object2[3]; yp[0] = new Object(5); yp[1] = new Object(6); yp[2] = new Object(8); staticMethods.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

How array works in JavaScript?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 . JavaScript array-copy operations create shallow copies.


2 Answers

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"] 
like image 93
Martin R Avatar answered Oct 14 '22 16:10

Martin R


    for item in items {         item.instanceMethod()     } 
like image 30
orkoden Avatar answered Oct 14 '22 16:10

orkoden