[问题]
从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’
如图:
[解决过程]
1.搜:
swift Value of type [UIViewController] has no member indexOfObject
参考:
ios – Xcode error "value of type ‘[UIViewController]’ has no member ‘firstObject’" – Stack Overflow
2.搜:
swift UIViewController indexOfObject
参考:
都说了:
“这是一个辅助函数,用于在一个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