Closed. This question is opinion-based。它目前不接受答案。
想改进这个问题吗?更新问题,以便editing this post可以用事实和引用来回答。
三年前关闭。
在Objective-C中,通常使用布尔指针来停止枚举,例如:
[myArray rh_iterate:^(id element, int index, BOOL *stop){
    // Do cool stuff
    *stop = YES;
}];

我已经这样实现了:
// This is in a category of NSArray
- (void)rh_iterate:(void (^)(id, int, BOOL *))block
{
    if (!block) { return; }

    BOOL stop = NO;
    for (int i = 0; i < self.count; i++) {
        block(self[i], i, &stop);
        if (stop) { return; }
    }
}

我现在正在Swift中实现我的版本,但不依赖任何Objective-C源代码。我知道swift喜欢限制指针的访问,所以最好的实现方法是什么?(理想情况下完全避免指针。)
编辑:
最直接的方法是:
func rh_iterate(callback: (Element, Int, UnsafeMutablePointer<Bool>) -> ()) {

        var stop: Bool = false
        for (index, element) in self.enumerate() {
            callback(element, index, &stop)
            if stop { return }
        }
    }

最佳答案

既然他的答案被删除了,我就把它放回去。
BOOL*模式直接等价的是inout变量

extension Array
{
    func iterateWithStop(closure: (Element, inout shouldStop: Bool) -> ()) -> Bool
    {
        var shouldStop = false
        for e in self
        {
            guard !shouldStop else { return false }
            closure(e, shouldStop: &shouldStop)
        }
        return !shouldStop
    }
}

如果迭代在闭包尝试停止的情况下完成,则函数返回true;如果闭包确实尝试停止,则函数返回false。
您可以这样使用它:
let myArray = [1, 2, 3,  -1, 4]

var sum = 0
let didProcessAllElements = myArray.iterateWithStop{ e, shouldStop in
    if e < 0
    {
        shouldStop = true
    }
    else
    {
        sum += e
    }
}

// sum == 6

(在斯威夫特2.2的操场上测试)

关于objective-c - 在Swift中实现指针的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37706412/

10-12 00:22
查看更多