2017-11-01 14 views
0

に型「Swift._SwiftDeferredNSDictionary 」の値をキャストできませんでした別のクラスから)それはgetMutablePlistDict(というメソッドを呼び出します は、私はスウィフト3.0でアプリケーションを書かれていると私は次のデータ型を宣言した「NSMutableDictionary」

// Connect to plist and get the data 
    if let plist = PlistHandler(name: "MovieData") { 
     getPlist = plist.getMutablePlistDict()! 

     // Load the movie items into the table view data source 
     for i in 0..<getPlist.count { 
      movieItems = (getPlist.object(forKey: "Item\(i)") as! NSMutableDictionary) as! [String: String] as! NSMutableDictionary 
      let newName = movieItems.object(forKey: "Name") 
      let newRemark = movieItems.object(forKey: "Remark") 
      if newName as? String != "" { 
       movies.append(Movie(name: newName as? String, remark: newRemark as? String) 
      )} 
     } 
    } else { 
     print("Unable to get Plist") 
    } 

::私はplistの内容をロードしている次のような方法があります

// Get the values from plist -> MutableDirectory 
func getMutablePlistDict() -> NSMutableDictionary? { 

    let fileManager = FileManager.default 

    if fileManager.fileExists(atPath: destPath!) { 
     guard let dict = NSMutableDictionary(contentsOfFile: destPath!) else { return .none } 
     return dict 
    } else { 
     return .none 
    } 
} 

私は、アプリケーションを実行すると上記のエラーが表示されます(質問タイトルを参照)。しかしこれは新しいものです。 Xcode 8ではこのエラーは発生しませんでした。これの理由は何ですか?それを避けるためにコードを変更する必要がありますか?

あなたはこのように使用することができます
+1

構文 'として! NSMutableDictionary)として! [String:String]として! NSMutableDictionary'は恐ろしいです。エラーメッセージはかなり明確です。 Swift辞書を 'NSMutableDictionary'にキャストすることはできません。 ** Swiftでは 'NSMutable ...'コレクション型を使用しないでください**。辞書を '[String:String]'として宣言してください。 'var'キーワードを使うと、自由に変更可能です。そして、代わりに 'NSMutableDictionary(contentsOfFile'は' PropertyListSerialization'を使用します。 – vadian

+0

ヒントありがとうございます! – Martin

答えて

0

変更NSMutableDictionary[String: Any]へ:

var movies = [Movie]() 
var getPlist: [String: Any] = [:] 
var movieItems: [String: Any] = [:] 


func getMutablePlistDict() -> [String: Any] { 
    let fileManager = FileManager.default 

    if fileManager.fileExists(atPath: destPath!) { 
     if let dict = NSDictionary(contentsOfFile: destPath!) as? [String: Any] { 
      return dict 
     } 
    } else { 
     return [:] 
    } 
} 

if let plist = PlistHandler(name: "MovieData") { 
     let getPlist = plist.getMutablePlistDict() 

     // Load the movie items into the table view data source 
     for i in 0..<getPlist.count { 
      if let movieItemsCheck = getPlist["Item\(i)"] as? [String: Any] { 
       movieItems = movieItemsCheck 
       if let newName = movieItems["Name"] as? String, let newRemark = movieItems["Remark"] as? String, newName != "" { 
        movies.append(Movie(name: newName, remark: newRemark)) 
       } 
      } 
     } 
    } else { 
     print("Unable to get Plist") 
    } 
+0

うまく動作しますが、 – Martin

関連する問題