【问题标题】:Getting error's in swift 3 xcode 8在 swift 3 xcode 8 中出现错误
【发布时间】:2016-10-05 06:48:59
【问题描述】:

我已在 Xcode 中将旧的 Swift 代码转换为新的 Swift3。现在它在我的 Swift 文件中显示这些错误:

self.detailViewController = controllers[controllers.count- 1].topViewController as? DetailViewController

错误:

“UIViewController”类型的值没有成员“topViewController”

let sortedTimes = sorted(times!){a,b in a.0.rawValue < b.0.rawValue}

错误:

'sorted' 不可用:在集合上调用 sort() 方法

【问题讨论】:

  • 试试这个 self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController

标签: ios swift xcode swift3 xcode8


【解决方案1】:

第一个可能是您的UINavigationController 被放入UIViewControllers 的集合中。你需要让编译器知道它确实是一个UINavigationController。

self.detailViewController = (controllers[controllers.count - 1] as? UINavigationController)?.topViewController as? DetailViewController

第二个是sorted函数现在变成了实例方法。

let sortedTimes = times!.sorted { $0.0.rawValue < $1.0.rawValue }

【讨论】:

  • 第二个修复程序消除了错误,但接下来的几行给了我一个错误,任何想法 todayTimes = sortedTimes tableView.reloadData(sorted)
  • 您在@sabrefm1 的下一行遇到什么错误?
【解决方案2】:

使用这条线,

let sortedTimes = times.sort({a,b in a.0.rawValue < b.0.rawValue})

希望这会对你有所帮助。

【讨论】:

    【解决方案3】:

    Swift 具有在编译时完成的type safety 功能。 controllers[controllers.count - 1 必须是 UINavigationController 类型。所以你必须相应地投射它。

    self.detailViewController = (controllers[controllers.count - 1] as? UINavigationController)?.topViewController as? DetailViewController
    

    假设集合(数组)包含 int 值。

    let times : NSArray = [1,2,3,4]
    let sortedTimes = times.sorted(by: {a,b in (a as! Int) < (b as! Int)})
    

    您可以将 as! 向下转换更新为您指定的类型 ({a,b in (a as AnyObject).rawValue &lt; b.0.rawValue})。

    【讨论】:

    • 技术上说 Swift 3 是类型安全的并没有错。然而,AFAIK,Swift 一直是类型安全的。
    • 第一个答案是正确的,但我在第二次调用 sort() 方法时似乎仍然出错
    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多