Getting Name of ObjC Enum in Swift 3?

前端 未结 3 1907
野的像风
野的像风 2021-01-05 10:55

If an ObjC function returns a status value with enum, is there way to get the string of the enum in Swift 3? If I do debugPrint(\"\\(status)\"), or print(

3条回答
  •  失恋的感觉
    2021-01-05 11:12

    If print(x) gives you what you want, then use String(describing:). This is almost always the correct answer. (Generally speaking, this will be equivalent to "\(x)". They don't have to be the same, but I haven't found a case yet where they're not.) If only debugPrint() gives you what you want, then use String(reflecting:).

    Be very careful with these results. They are not localized and not promised to remain consistent between releases. They are not a serialization API. There's no promise they can be reversed to give you the original data. The output of these methods for enums changed dramatically in Swift 3. I absolutely expect them to change again as Foundation is refined further for Swift.

    I don't want to over-scare you about these methods. String(describing:) is pretty well defined about what it returns in some cases (particularly custom types that implement certain protocols), but not in all cases. You have to read the docs and have reasonable caution around it. On the other hand String(reflecting:) is explicitly "suitable for debugging." I wouldn't bet on anything about this string.

提交回复
热议问题