OTUnwrapper
展开可选和 JSON 值
目录
要求
- iOS 8.0+
- Xcode 9.4+
- Swift 4.2+
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。你可以使用以下命令安装它:
$ gem install cocoapods
要使用 CocoaPods 将 GAInfiniteCollectionKit-iOS 集成到你的 Xcode 项目中,请在你的 Podfile 中指定它:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'OTUnwrapper'
end
然后,运行以下命令:
$ pod install
机会
- 展开可选
- 将数据展开为 JSON
- 展开 JSON 值
- 将 JSON 展开为对象
- 使用默认值展开
如何使用
导入
import OTUnwrapper
展开可选值
##不使用默认值:如果你不使用默认值,你需要指定值类型 你有两种方式来展开可选值
var optionalString : String?
var optionalString2 : String?
optionalString2 = "String is not nil"
let value : String = optionalString.unwrap() // value = ""
let value2 : String = optionalString.unwrap() // value2 = "String is not nil"
##使用默认值:如果你使用默认值,你不需要指定值类型
var optionalString : String?
var optionalString2 : String?
optionalString2 = "String is not nil"
let value = optionalString.unwrap("Value is nil") // value = "Value is nil"
let value2 = optionalString2.unwrap("Value is nil") // value2 = "String is not nil"
将数据解包为JSON
示例
let data = [DATA]
let json = data.unwrapToJSON()
解包JSON值
示例
let json: [String:Any] = ["name": "OTUnwrapper", "URL" : "https://github.com/OlegTsib/OTUnwrapper","liked": true]
let name: String = json.unwrapValue("name") // name = "OTUnwrapper"
let liked = json.unwrapValue("liked",false) // liked = true
解包JSON对象
第一步
创建类或结构体并实现协议 OTUnwrappedObject
示例
结构体 User
import OTUnwrapper
struct User: OTUnwrappedObject
{
let name : String
let imageURI : String
init(dictionary: [String : Any])
{
email = dictionary.unwrapValue("name")
imageURI = dictionary.unwrapValue("image")
}
}
JSON 文件
{
"user":
{
"name ": "OTUnwrapper",
"image": "https://avatars0.githubusercontent.com/u/15246986?s=400&v=4"
}
}
展开为对象
guard let path = Bundle.main.path(forResource: "FileName", ofType: "json") else { return }
do
{
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let json = data.unwrapToJSON()
let user: User = json.unwrapToObject("user")
}
catch
{
}
作者
许可协议
OTUnwrapper 采用 MIT 许可协议。更多信息请参阅 LICENSE 文件。