NSArray必须- (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp确定排序数组中新对象的插入位置.
在纯Swift中执行此操作的最佳和高性能方法是什么?
有点像:
var myArray = ["b", "e", "d", "a"]
myArray.sort { $0 < $1 }
// myArray is now [a, b, d, e]
myArray.append("c")
myArray.sort { $0 < $1 }
// myArray is now [a, b, c, d, e]
Run Code Online (Sandbox Code Playgroud)
我想找出正确的位置并插入元素,而不是追加新元素然后对数组进行排序:
let index = [... how to calculate this index ??? ...]
myArray.insert("c", atIndex: index)
Run Code Online (Sandbox Code Playgroud) 在类声明中,使用<>尖括号和swift中声明的参数是什么?像:
public class ClassName<T: Comparable> {
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试转换以下Swift 2.3代码:
//Example usage:
//(0 ..< 778).binarySearch { $0 < 145 } // 145
extension CollectionType where Index: RandomAccessIndexType {
/// Finds such index N that predicate is true for all elements up to
/// but not including the index N, and is false for all elements
/// starting with index N.
/// Behavior is undefined if there is no such N.
func binarySearch(predicate: Generator.Element -> Bool)
-> Index {
var low = startIndex
var high = endIndex
while low …Run Code Online (Sandbox Code Playgroud)