在数组中的每个对象上调用实例方法

时间:2015-12-14 13:36:02

标签: swift

让我们假设这种情况:我有一个对象数组,我想在每个对象上调用实例方法。我可以这样做:

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

同样的情况是map。例如,我想用mappingInstanceMethod将每个对象映射到其他对象,返回值:

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

有更清洁的方法吗?

例如在Java中可以做到:

items.forEach(Item::instanceMethod);

而不是

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

Swift中是否提供类似的语法?

3 个答案:

答案 0 :(得分:44)

你在做什么

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

是一种干净又快捷的方式。正如Is there a way to reference instance function when calling SequenceType.forEach?中所解释的那样,第一个陈述不能减少 到

items.forEach(Item.instanceMethod)

但有一个例外:它适用于init方法 这只需要一个参数。例如:

let ints = [1, 2, 3]
let strings = ints.map(String.init)
print(strings) // ["1", "2", "3"]

答案 1 :(得分:2)

    for item in items {
        item.instanceMethod()
    }

答案 2 :(得分:2)

你试过吗

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

请注意()调用方法

编辑1:

示例代码:

class SomeObject {

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

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

let ints = array.map { $0.someFunction()}
print(ints)
相关问题