【发布时间】:2015-01-05 20:18:04
【问题描述】:
在将以下代码翻译成 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”中的“title”
上面的两个错误我没看懂。
【问题讨论】: