如何在Swift中使用CFBinaryHeap?

时间:2015-08-23 00:58:27

标签: swift core-foundation

我搜索过,找不到使用Swift代码中的CFBinaryHeap的示例,所以我将我的示例发布为以下答案。

1 个答案:

答案 0 :(得分:1)

这是一个使用CFBinaryHeap存储来自Swift的Foo结构的示例,按整数属性排序。

struct Foo {
    var x : Int = 0
}

var callbacks = CFBinaryHeapCallBacks()

// <Foo> comparator
callbacks.compare = { (a,b,unused) in
    let afoo : Foo = UnsafePointer<Foo>(a).memory
    let bfoo : Foo = UnsafePointer<Foo>(b).memory

    if ( afoo.x == bfoo.x ) { return CFComparisonResult.CompareEqualTo }
    if ( afoo.x > bfoo.x ) { return CFComparisonResult.CompareGreaterThan }
    return CFComparisonResult.CompareLessThan
}

let callbackPointer = UnsafeMutablePointer<CFBinaryHeapCallBacks>.alloc(1)
callbackPointer.initialize(callbacks)
var bh = CFBinaryHeapCreate(nil, 0, callbackPointer, nil)

var fooPointer : UnsafeMutablePointer<Foo>!
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 42))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 99))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 2))
CFBinaryHeapAddValue(bh, fooPointer)

var got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 2
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 42
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 99
CFBinaryHeapRemoveMinimumValue(bh)