2015-12-19 49 views
1

我只是遷移我的雨燕1.2的代碼斯威夫特2碼,我得到了錯誤錯誤:的UIViewController「式的價值‘’沒有成員‘的className’

值類型 「UIViewController」 的對這個線路沒有構件 'className'

if(childViewController.className=="myPhotoCalendar.GalleryController")

這裏是我的代碼:

func initLeftMenuController() 
{ 
    for childViewController in self.childViewControllers 
    { 
     if(childViewController.className=="myPhotoCalendar.GalleryController") 
     { 
      self.galleryController=childViewController as! GalleryController 
     } 
     if(childViewController.className=="myPhotoCalendar.TextsController") 
     { 
      self.textsController=childViewController as! TextsController 
     } 
     if(childViewController.className=="myPhotoCalendar.TemplatesController") 
     { 
      self.templatesController=childViewController as! TemplatesController 
     } 
     if(childViewController.className=="myPhotoCalendar.StylesController") 
     { 
      self.stylesController=childViewController as! StylesController 
     } 
     if(childViewController.className=="myPhotoCalendar.ObjektsController") 
     { 
      self.objektsController=childViewController as! ObjektsController 
     } 
    } 
} 

人有className斯威夫特2當量的想法? 感謝您的幫助。

回答

1

檢查類名相似性根本不是一個好主意 - 用if let代替。如果你改變一個班的名字,你會怎麼做?這可能不會通過重構來覆蓋,應用程序將停止工作。

因此最好的解決辦法是不是找對className替代,但使用更好,更「SWIFTY」的方式 - 像

if let ctrl = childViewController as? GalleryController { 
    self.galleryController = ctrl 
} else if (...) { 
    ... 
} 

或者使用switch語句(如馬丁說)(我做到了不知道是可能的,直到查找它):

switch childViewController { 
case let ctrl as GalleryController: 
    self.galleryController = ctrl 
case let ctrl as SomeOtherClass: 
    self.something = ctrl 
// more cases 
default: 
    break 
} 
+1

...或一個switch語句。 –

+0

@MartinR不知道那個 - 總是很高興學習新東西:) – luk2302

+0

非常感謝,它的工作原理! – Zipette

相關問題