无法转换类型&#39; Swift._SwiftDeferredNSDictionary的值<swift.string,swift.string =“”>&#39;到&#39; NSMutableDictionary&#39;

时间:2017-11-01 09:42:32

标签: ios swift3 nsdictionary

我有一个用Swift 3.0编写的应用程序,我声明了以下数据类型:

var movies = [Movie]()
var getPlist = NSMutableDictionary()
var movieItems = NSMutableDictionary()

我有以下方法加载plist的内容:

// 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")
    }

它从另一个类调用一个名为getMutablePlistDict()的方法:

// 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 个答案:

答案 0 :(得分: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")
    }