我正在快速扩展Array
课程。我需要对数组进行排序,但是当我尝试它时会给出错误Immutable value of type 'Array<T>' only has mutating members named 'sort'
这是我的扩展名:
import UIKit
extension Array {
func sortedArrayByTimeUsingKey(key: String, ascending: Bool) {
sort { (firstObject, secondObject) -> Bool in
let firstDict = firstObject as [String: AnyObject]
let secondDict = secondObject as [String: AnyObject]
let firstDateString = firstDict[key]! as String
let secondDateString = secondDict[key]! as String
let dateFormatter = DateFormatter()
let firstDate = dateFormatter.dateFromString(firstDateString)!
let secondDate = dateFormatter.dateFromString(secondDateString)!
let order = firstDate.compare(secondDate)
switch order {
case .OrderedAscending:
return ascending ? true : false
case .OrderedDescending:
return ascending ? true : false
default:
return true
}
}
}
}
如何将self
变为可变或如何检查self
是否可变?
答案 0 :(得分:2)
如果方法修改了实例本身,则该方法需要是一个变异的方法。所以只需在func。
之前添加mutating关键字答案 1 :(得分:1)
刚刚找到了答案:在mutating
func