【问题标题】:Swift3: not the expected contextual result type NSArraySwift3:不是预期的上下文结果类型 NSArray
【发布时间】:2017-01-05 03:02:43
【问题描述】:

我正在将我的代码从 Swift 2.3 迁移到 Swift 3。在迁移后它工作正常之前,我面临着非预期的上下文结果类型 NSArray 这是我的代码

func setConfirmedBookingsAfterSorting() {
        if let bookings =  ContentService.sharedInstance.confirmedBookings {
            self.confirmedBookings = (bookings as NSArray).sortedArray(using: [NSSortDescriptor(key: "startTime", ascending: true)])
        }
    }

【问题讨论】:

  • 为什么不直接使用 Swift 的原生排序呢? bookings.sort{ $0.startTime < $1.startTime }

标签: swift3 nsarray nssortdescriptor


【解决方案1】:

使用的方法的声明类型是func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any],这意味着结果被隐式转换为Swift数组。

试试这个:

((bookings as NSArray).sortedArray(using: [NSSortDescriptor(key: "startTime", ascending: true)])) as NSArray

这会阻止转换并将结果保存为NSArray Objective C 对象。

【讨论】:

  • 这看起来明显比Alexander's suggestion复杂:你能描述一下优点吗?
  • @greybeard - 这是对问题中代码的最小修改,而不是评论中的建议,有些人可能更喜欢。具体来说,它不需要更改任何声明的类型,也不会将行为从返回排序副本更改为就地排序。
  • @brimstone - 使用的方法的声明类型是func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any],这意味着结果被隐式转换为 Swift 数组。这可以防止转换并将结果保持为NSArray Objective C 对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多