Swift:语法翻译

标签 swift xcode6 xcode6.1

需要帮助将下面的代码翻译成 Swift。

Objective-C 代码(效果很好):

- (UIViewController *)getViewControllerFromStoryboard:(NSString *)storyboardName sceneName:(NSString*)sceneName iconName:(NSString*)icon title:(NSString*)title
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:sceneName];
    UIImage *tabIcon = [UIImage imageNamed:icon];

    vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:tabIcon selectedImage:nil];
    vc.title = NSLocalizedString(title,nil);

    return vc;
}

翻译为 Swift:

func getViewControllerFromStoryBoar(storyboardName: String, sceneName: String, iconName: String, title: String) -> UIViewController{
    let sb : UIStoryboard = UIStoryboard(name: storyboardName, bundle: nil)
    let vc = sb.instantiateViewControllerWithIdentifier(sceneName)  //Warning A
    let tabIcon : UIImage = UIImage(named: iconName)!
    vc.tabBarItem = UITabBarItem(initWithTitle:title, image:tabIcon) //Error A
    vc.title = title //Error B

    return vc as UIViewController

}

警告 A: 常量“vc”被推断为“AnyObject!”类型,这可能是意外的 为什么是“任何对象!” ?这似乎修复了错误

错误 A:无法分配给“vc”中的“tabBarItem”

错误 B:无法分配给“vc”中的“标题”

我不明白上面的两个错误。

最佳答案

Error A: Cannot assign to 'tabBarItem' in 'vc'

Error B: Cannot assign to 'title' in 'vc'

因为instantiateViewControllerWithIdentifier返回一个AnyObject。这就是警告警告你的!您应该注意该警告。 (您压制了警告;这是错误的做法。不要压制它;它。)

您需要先强制转换此引用,然后才能使用它。我知道知道它是一个 UIViewController,但 Swift 不知道这一点;你必须转换并讲述它。

let vc = sb.instantiateViewControllerWithIdentifier(sceneName) as UIViewController

这样一来,整个问题就解决了。

关于Swift:语法翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27787214/

相关文章:

ios - 使用 swift 更改 UIView 中的文本调整

ios - 无法将视频保存到照片库

xcode - 查找 "Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0"的原因

ios - Xcode 6.1 构建在设备上崩溃

ios - definesPresentationContext 应设置为 YES,但在与 UISearchController 结合使用时会中断导航

swift - 使 NSDecimalNumber 可编码

ios - 为 HexColors (2.3.0) 安装 podfile 后的词法或预处理器问题

ios - xcode 6.1不添加文档类型

ios - Swift:iOS Facebook 版本编译器错误

Xcode 6.01 iOS Simulator 8.0 无皮肤且在 Retina Macbook Pro 上太小