NSDictionary to NSData and NSData to NSDictionary in Swift

前端 未结 6 1462
故里飘歌
故里飘歌 2020-12-12 23:54

I am not sure if I am using the dictionary or the data object or both incorrectly. I m trying to get used to the switch to swift but I\'m having a little trouble.

         


        
6条回答
  •  被撕碎了的回忆
    2020-12-13 00:33

    Swift 5

    as @yuyeqingshan said, PropertyListSerialization is a good option

           // Swift Dictionary To Data.
            do {
                let data = try PropertyListSerialization.data(fromPropertyList: [:], format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
                // do sth
            } catch{
                print(error)
            }
    
    
            // Data to Swift Dictionary
            do {
                let dicFromData = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil)
                if let dict = dicFromData as? [String: Any]{
                    // do sth
                }
            } catch{
                print(error)
            }
    

提交回复
热议问题