Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active November 17, 2017 11:43
Show Gist options
  • Save acalism/a683d13c7c9076cb03c7361ff61d8167 to your computer and use it in GitHub Desktop.
Save acalism/a683d13c7c9076cb03c7361ff61d8167 to your computer and use it in GitHub Desktop.
Alternative for String(describing:) or String(reflecting:)
// MARK: - Optional Unwrap 并转化为字符串
extension String {
enum UnwrapType {
case describing
case reflecting
}
/// 将任意的Optional类型转化为String,并不会用Optional(abc)这样的包裹形式
///
/// - Parameter unwrap: 需要被unwrap的类型
/// - Parameter type: unwrap的两种方式,其中reflecting方式会更详细
/// - Returns: 转为String后的结果
init<Subject>(unwrap instance: Subject?, type: UnwrapType = .describing) {
guard let i = instance else {
self.init("nil")
return
}
switch type {
case .describing:
self.init(describing: i)
case .reflecting:
self.init(reflecting: i)
}
}
var length: Int {
get { return self.characters.count }
}
}
// example
//struct Point {
// let x: Int, y: Int
//}
//let s: Point? = Point(x: 3, y: 4)
//print(String(unwrap: s))
//print(String(unwrap: s, type: .reflecting))
//print(String(describing: s))
//print(String(reflecting: s))
// 输出(test是module名字):
// Point(x: 3, y: 4)
// test.Point(x: 3, y: 4)
// Optional(test.Point(x: 3, y: 4))
// Optional(test.Point(x: 3, y: 4))
@acalism
Copy link
Author

acalism commented Oct 16, 2017

// Is this what you want? 这个结果是你想要的吗?
let a: String? = ""
print(String(describing: a)); 
// Optional("") 
// 也许你并不想要这个 Optional()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment