SwiftyOptional
使用
SwiftyOptional 帮助您在使用可选类型并进行工作以获得包装值(如使用 ?? 获取包装值)时,例如,获取可选数组中的第一个元素,而不是像这样获取第一个元素
// Array
var countries: [String]? = ["Egypt", "Iraq", "Kwuit"]
let wrappedCountries: [String] = countries ?? []
let firstCountry = wrappedCountries.first ?? ""
您可以这样获取第一个元素
// Array
let countries: [String]? = ["Egypt", "Iraq", "Kwuit"]
let firstCountry = countries.swiftyArray.first.swiftyValue
print("First country: \(firstCountry)")
还可以与可选类型 String、Int、Float、Double 一起使用
// Optional types
let unwrappedString: String? = "Hello world!"
let unwrappedInt: Int? = 25
let unwrappedFLoat: Float? = 2.5
let unwrappedDouble: Double? = 100.6
// rather than using ??
print("""
Wrapped String: \(unwrappedString ?? "")
Wrapped Int: \(unwrappedInt ?? 0)
Wrapped Float: \(unwrappedFLoat ?? 0.0)
Wrapped Double: \(unwrappedDouble ?? 0.0)
""")
// you can get warpped value by using swiftyValue
print("""
Wrapped String: \(unwrappedString.swiftyValue)
Wrapped Int: \(unwrappedInt.swiftyValue)
Wrapped Float: \(unwrappedFLoat.swiftyValue)
Wrapped Double: \(unwrappedDouble.swiftyValue)
""")
// Also can set your default value when wrapped value is nil
print("""
Wrapped String: \(unwrappedString.swiftyDefault(value: "non")), set non if unwrappedString is nil
Wrapped Int: \(unwrappedInt.swiftyDefault(value: 1)), set 0 if unwrappedInt is nil
Wrapped Float: \(unwrappedFLoat.swiftyDefault(value: 1.5)), set 1.5 if unwrappedFLoat is nil
Wrapped Double: \(unwrappedDouble.swiftyDefault(value: 5.5)), set 5.5 if unwrappedDouble is nil
""")
// Also you can parse optional Any and get wrapped value
let username: Any? = "Bokhary"
let itemsOrderCount: Any? = 10
let totalPrice: Any? = 500.5
print("""
Parse Any to Wrapped String: \(username.swiftyString)
Parse Any to Wrapped Int: \(itemsOrderCount.swiftyInt)
Parse Any to Wrapped Double: \(totalPrice.swiftyDouble)
""")
// Can parse between types
let tenTimes: String? = "10"
let feeCost: Int? = 200
print("""
Parse Optioanl String to Wrapped Int: \(tenTimes.intValue)
Parse Optional Int to Wrapped Double: \(feeCost.doubleValue)
""")
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录中运行 pod install
要求
Swift 4.2,Xcode 10 及更高版本。
安装
SwiftyOptional 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'SwiftyOptional'
作者
bokhary3, [email protected]
许可协议
SwiftyOptional 在 MIT 许可协议下可用。更多信息请查看 LICENSE 文件。