最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]Swift中代码出错:Value of type [UIViewController] has no member indexOfObject

Swift crifan 2440浏览 0评论

[问题]

从OC转换为swift的代码:

    var selectedViewController:UIViewController?

    var viewControllers = [UIViewController]()
    {
        willSet(newViewControllers){

            let oldSelectedViewController:UIViewController = self.selectedViewController!
            let newIndex:UInt = viewControllers.indexOfObject(oldSelectedViewController)

出错:

Value of type ‘[UIViewController]’ has no member ‘indexOfObject’

如图:

Value of type UIViewController has no member indexOfObject

 

[解决过程]

1.搜:

swift Value of type [UIViewController] has no member indexOfObject

参考:

ios – Xcode error "value of type ‘[UIViewController]’ has no member ‘firstObject’" – Stack Overflow

ios – UIViewController no longer has members topViewController or viewControllers in XCode 7 – Stack Overflow

2.搜:

swift  UIViewController indexOfObject

参考:

使用多个storyboard管理TabBar的内容

都说了:

“这是一个辅助函数,用于在一个array中寻找某个对象,并返回它的队列下标,相当于NSArray的indexOfObject(swift的Array没有对应的函数)”

ios – viewControllers indexOfObject in swift – Stack Overflow

去试试IndexOf

(其实自己之前就手动试了试,结果发现一堆提示,说Index没法给UInt,所以放弃了)

结果现在再去试试,最后搞定了:

let newIndex:UInt = UInt(viewControllers.indexOf(oldSelectedViewController)!)

就可以了。

[总结]

Swift中,UIViewController的Array没有了OC中的indexOfObject

解决办法是,换成indexOf,不过要注意的是,此处返回的是Index,而不是UInt,所以要强制转换为UInt,此处的代码:

    var viewControllers = [UIViewController]() {
        willSet(newViewControllers){
            let oldSelectedViewController:UIViewController = self.selectedViewController!
            let newIndex:UInt = UInt(viewControllers.indexOf(oldSelectedViewController)!)
    }

供参考。

转载请注明:在路上 » [已解决]Swift中代码出错:Value of type [UIViewController] has no member indexOfObject

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
72 queries in 0.092 seconds, using 18.88MB memory