需要帮助将以下代码翻译成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;
}
翻译到斯威夫特:
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!',这可能是意外的 为什么' AnyObject!' ?这似乎解决了错误
错误A:无法分配给' tabBarItem'在' vc'
错误B:无法分配到'标题'在' vc'
我不理解上面的两个错误。
答案 0 :(得分:1)
错误A:无法分配到' tabBarItem'在' vc'
错误B:无法分配到'标题'在' vc'
因为instantiateViewControllerWithIdentifier
返回AnyObject。这就是警告警告你的!你应该注意那个警告。 (你沉默了警告;这是错误的事情。不要让它沉默; 听它。)
在使用它之前,您需要先删除此引用。我知道你知道它是一个UIViewController,但是Swift并不知道这个;你必须施展并告诉它。
let vc = sb.instantiateViewControllerWithIdentifier(sceneName) as UIViewController
这将一举解决整个问题。