Created
December 4, 2017 06:55
-
-
Save jianghaoyuan2007/3f79f21828b90e869e70e1b5a34ca99c to your computer and use it in GitHub Desktop.
The extensions for Optional type in Swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Optional { | |
var wrappedObject: Wrapped? { | |
if let object = self { return object } | |
return nil | |
} | |
} | |
extension Optional { | |
public var string: String? { | |
if let string = self.wrappedObject as? String { return string } | |
return nil | |
} | |
public var stringValue: String { return self.string ?? "" } | |
} | |
extension Optional { | |
public var int: Int? { | |
if let int = self.wrappedObject as? Int { return int } | |
return nil | |
} | |
public var intValue: Int { return self.int ?? 0 } | |
} | |
extension Optional { | |
public var bool: Bool? { | |
if let bool = self.wrappedObject as? Bool { return bool } | |
return nil | |
} | |
public var boolValue: Bool { return self.bool ?? false } | |
} | |
extension Optional { | |
public var double: Double? { | |
if let double = self.wrappedObject as? Double { return double } | |
return nil | |
} | |
public var doubleValue: Double { return self.double ?? 0.0 } | |
} | |
extension Optional { | |
public var float: Float? { | |
if let float = self.wrappedObject as? Float { return float } | |
return nil | |
} | |
public var floatValue: Float { return self.float ?? 0 } | |
} | |
extension Optional { | |
public func extractArray<T>() -> [T]? { | |
if let array = self.wrappedObject as? [T] { return array } | |
return nil | |
} | |
public func extractArrayValue<T>() -> [T] { | |
return self.extractArray() ?? [T]() | |
} | |
} | |
extension Optional { | |
public func extractDictionary<Key, Value>() -> [Key: Value]? { | |
if let dictionary = self.wrappedObject as? [Key: Value] { return dictionary } | |
return nil | |
} | |
public func extractDictionaryValue<Key, Value>() -> [Key: Value] { | |
return self.extractDictionary() ?? [Key: Value]() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment