Swift:无法为“[UIViewController]"类型的值添加下标? [英] Swift: Cannot subscript a value of type '[UIViewController]?'

查看:26
本文介绍了Swift:无法为“[UIViewController]"类型的值添加下标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在 Xcode 7 (iOS9) 上的 Swift 中解决这个问题,但我也遇到了这个错误:

I am trying to figure out how to fix this issue in Swift on Xcode 7 (iOS9) and I am also having this error:

无法为[UIViewController]"类型的值添加下标?索引类型为Int"

Cannot subscript a value of type '[UIViewController]?' with an index of type 'Int'

任何建议表示赞赏.谢谢.

Any suggestion appreciated. Thanks.

我的代码:

func indexPositionForCurrentPage(pageViewController: UIPageViewController) -> Int {

    let currentViewController = pageViewController.viewControllers[0] as UIViewController

    for (index, page) in pages.enumerate() {
        if (currentViewController == page) {

            return index
        }
    }

    return -1
}

推荐答案

尝试:

let currentViewController = pageViewController.viewControllers![0]

不过,这样写会更安全:

It would be safer, though, to write:

if let currentViewController = pageViewController.viewControllers?[0] {
    // ... and then do everything else in the if-block
end

另一种选择:

guard let currentViewController = pageViewController.viewControllers?[0] else { 
    return 
}
// ... and then just proceed to use currentViewController here

这样做的优点是它是安全的,但不需要将函数的其余部分放在 if 块中.

This has the advantage that it's safe but there's no need to put the remainder of the function inside an if block.

这篇关于Swift:无法为“[UIViewController]"类型的值添加下标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆