Created
December 4, 2015 15:51
-
-
Save alekseypotapov-dev/a372fe33f4685377ee87 to your computer and use it in GitHub Desktop.
Swift with C example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//original video https://realm.io/news/pragma-chris-eidhof-swift-c/ | |
import Foundation | |
extension Comparable { | |
static func compare (l: UnsafePointer<Void>, _ r: UnsafePointer<Void>) -> Int32 { | |
let left: Self = UnsafePointer(l).memory | |
let right: Self = UnsafePointer(r).memory | |
if left < right { return -1 } | |
if left == right { return 0 } | |
return 1 | |
} | |
} | |
typealias CompareFunc = (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 | |
func cmp(thunk: UnsafeMutablePointer<Void>, l: UnsafePointer<Void>, r: UnsafePointer<Void> ) -> Int32 { | |
let compareFunc: CompareFunc = UnsafeMutablePointer(thunk).memory | |
return compareFunc(l,r) | |
} | |
extension Array where Element: Comparable { | |
func quicksort() -> [Element] { | |
var array = self | |
var compare = Element.compare | |
qsort_r(&array, array.count, strideof(Element), &compare, cmp) | |
//here Chris recommends to use "strideof" instead of "sizeof" when working with C API. Because of different platform-specific bytes | |
return array | |
} | |
mutating func quicksortInline() { | |
self = quicksort() | |
} | |
} | |
var array = ["b", "A", "c", "A"] | |
array.quicksortInline() | |
print(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment