【问题标题】:Use PropertyListSerialization to Make a Dictionary in swift 2使用 PropertyListSerialization 在 swift 2 中制作字典
【发布时间】:2017-01-27 05:26:41
【问题描述】:

我正在尝试在 swift 2 中使用 PropertyListSerialization 制作字典。但它不断给出这个错误:

"can not convert value of type 'Int' to expected argument type 'NSPropertyListReadOptions' 

我的代码行是:

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {response,data,error in
          if data != nil {
            let datasourceDictionary = try! NSPropertyListSerialization.propertyListWithData(data! ,options:Int(NSPropertyListMutabilityOptions.Immutable.rawValue), format: nil)

还有这个:

let datasourceDictionary = try! NSPropertyListSerialization.propertyListWithData(data! ,options:Int(NSPropertyListMutabilityOptions.Immutable.rawValue), format: nil)

然后我必须遍历字典:

for(key, value): (AnyObject, AnyObject) in datasourceDictionary {
          let name = key as? String
          let url = NSURL(string:value as? String ?? "")
          if name != nil && url != nil {
            let photoRecord = PhotoRecord(name:name!, url:url!)
            self.photos.append(photoRecord)
          }
        }

【问题讨论】:

    标签: ios swift swift2


    【解决方案1】:

    你应该解开你的数据对象而不是检查它是否为零。您还需要实现 do try catch 错误处理而不是强制它:

    if let data = data {
        do {
            let datasourceDictionary = try NSPropertyListSerialization.propertyListWithData(data, options: .MutableContainersAndLeaves, format: nil)
            print(datasourceDictionary)
        } catch let error as NSError {
            print(error.code, error.domain)
        }
    }
    
    【解决方案2】:

    您无需将其更改为 Int:

     NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {response,data,error in
              if data != nil {
                let datasourceDictionary = try! NSPropertyListSerialization
                                                .propertyListWithData(data!,
                                                    options:NSPropertyListMutabilityOptions.Immutable, 
                                                    format: nil)
    

    还有这个:

    let datasourceDictionary = try! NSPropertyListSerialization
                                                .propertyListWithData(data! ,
                                                    options:NSPropertyListMutabilityOptions.Immutable,
                                                    format: nil)
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 2016-01-04
      • 2021-12-15
      • 2015-08-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多