2015-01-05 2 views
0

아래 코드를 Swift로 번역 할 때 도움이 필요합니다.스위프트 : 구문 번역

목표 - 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 

} 

경고의 '! AnyObject' 상수 'VC를'유형을 가지고 추론하는 예기치 않은 경우 일 수 있습니다. 이유 'AnyObject!' ? 이 오류를 해결하는 것

오류 A :은 'VC'에서 'tabBarItem'에 할당 할 수 없습니다

오류 B :은 'VC'

I 돈의 '제목'에 할당 할 수 없습니다 위의 두 가지 오류를 이해하지 못합니다.

답변

1

오류 A : 'VC'에서 'tabBarItem'

오류 B에 할당 할 수 없습니다 : instantiateViewControllerWithIdentifier는 AnyObject를 반환하기 때문에 'VC'에서 '제목'

에 할당 할 수 없습니다. 그것은 경고가 당신에게 경고했던 것입니다! 그 경고에주의를 기울여야했습니다. (당신은 경고를 침묵, 즉 할 수있는 잘못된 일이었다 그것을 침묵하지 마십시오. 그것에을들을 수 있습니다.)

당신과 함께 작업 할 수 있습니다 당신은이 참조를 캐스팅해야합니다. 나는 을 알고있다.은 UIViewController라는 것을 알고 있지만 Swift는 이것을 모른다. 당신은 그것을 캐스팅하고 말해야합니다.

let vc = sb.instantiateViewControllerWithIdentifier(sceneName) as UIViewController 

이렇게하면 모든 것을 한 번에 해결할 수 있습니다.