无法转换表达式'()'输入' UINavigationController?'

时间:2014-09-27 04:26:54

标签: swift xcode6

我无法解决AppDelegate.swift中的错误。

我收到了一条消息'无法转换表达式'()'输入' UINavigationController?'

任何人都给我建议吗?

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let tabBarController = UITabBarController()
    let alarmViewController = AlarmViewController(style: .Plain)
    let recorderViewController = RecorderViewController()
    let playViewController = PlayViewController()

    let tabController1 = UINavigationController(rootViewController: recorderViewController)
    tabController1?.tabBarItem = UITabBarItem(title: "Recorder", image: UIImage(named: "tabbar_microphone"), tag: 1)

    let tabController2 = UINavigationController(rootViewController: playViewController)
    tabController2?.tabBarItem = UITabBarItem(title: "Cheer me up!", image: UIImage(named: "tabbar_play"), tag: 2)

    let tabController3 = UINavigationController(rootViewController: alarmViewController!)
    tabController3?.tabBarItem = UITabBarItem(title: "Alarm", image: UIImage(named: "tabbar_alarm"), tag: 3)

    ******* here's a place I got the message 'Cannot convert the expression's type '()' to type 'UINavigationController?' *******
    tabBarController.viewControllers = [tabController1, tabController2, tabController3]

    window?.rootViewController = tabBarController
    window?.makeKeyAndVisible()
    return true
}

1 个答案:

答案 0 :(得分:2)

您的tabControllerX是所有选项(正如您似乎意识到的那样,因为您在分配?时将它们全部引用为UITabBarItem),因此您需要打开它们。最简单的方法,考虑到你如何构建它,只需更改行

tabBarController.viewControllers = [tabController1!, tabController2!, tabController3!]
// Unwrap tabControllers

我会以不同的方式做到这一点,因为我不喜欢让我的逻辑中的选项不知道他们是否为零,如

if let tabController1 = UINavigationController(rootViewController: recorderViewController)
    // Now you know it's a tabController!
    tabController1.tabBarItem = UITabBarItem(title: "Recorder", image: UIImage(named: "tabbar_microphone"), tag: 1) 
    // ...
} else {
    // what are you going to do if it's nil?
}