Last active
November 17, 2017 11:43
-
-
Save acalism/a683d13c7c9076cb03c7361ff61d8167 to your computer and use it in GitHub Desktop.
Alternative for String(describing:) or String(reflecting:)
This file contains 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
// 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)) |
Author
acalism
commented
Oct 16, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment