Swift 字典与字符串互转 Dictionary To String

2022年7月28日 168点热度 0人点赞 0条评论

Swift 字典与字符串互转 Dictionary To String

 

字典转字符串 Dictionary To String
字符串转字典 String To Dictionary

 

字典转字符串 Dictionary To String
工具类:

// MARK: 字典转字符串
func dicValueString(_ dic:[String : Any]) -> String?{
    let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
    let str = String(data: data!, encoding: String.Encoding.utf8)
    return str
}

 

或者做成扩展:

// MARK: 字典转字符串
extension Dictionary {
    
    func toJsonString() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self,
                                                     options: []) else {
            return nil
        }
        guard let str = String(data: data, encoding: .utf8) else {
            return nil
        }
        return str
     }
    
}

 

 

字符串转字典 String To Dictionary
工具类

// MARK: 字符串转字典
func stringValueDic(_ str: String) -> [String : Any]?{
    let data = str.data(using: String.Encoding.utf8)
    if let dict = try? JSONSerialization.jsonObject(with: data!,
                    options: .mutableContainers) as? [String : Any] {
        return dict
    }

    return nil
}

或者做成扩展

// MARK: 字符串转字典
extension String {
    
    func toDictionary() -> [String : Any] {
        
        var result = [String : Any]()
        guard !self.isEmpty else { return result }
        
        guard let dataSelf = self.data(using: .utf8) else {
            return result
        }
        
        if let dic = try? JSONSerialization.jsonObject(with: dataSelf,
                           options: .mutableContainers) as? [String : Any] {
            result = dic
        }
        return result
    
    }
    
}

 

 


 

原文标题:Swift 字典与字符串互转 Dictionary To String
原文作者:绍清_shao
原文链接:https://www.jianshu.com/p/ca837975132c
原文快照:Swift 字典与字符串互转 Dictionary To String PDF

帮助教程

提供最新的帮助教程,方便使用。

文章评论