Swift:如何查看 Xcode 监视窗口中显示的变量值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24152252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:03:23  来源:igfitidea点击:

Swift: How to view the values of variables displayed in Xcode's watch window?

xcodeswift

提问by Gruntcakes

Simple question - how can you view the values of variables in Xcode's watch window when using Swift?

一个简单的问题 - 使用 Swift 时如何在 Xcode 的监视窗口中查看变量的值?

Here's an example, see how mdn has the value 2067134273 yet its not possible to view that in the watch window (ObjectiveC.NSObject doesn't expand to anything).

这是一个示例,看看 mdn 的值是 2067134273 是如何在监视窗口中查看的(ObjectiveC.NSObject 不会扩展到任何内容)。

enter image description here

在此处输入图片说明

I thought this might be due to the fact that its an optional, however its not that straightforward because look at the display of onss which is displayed as "Optional NSString", its possible to view that and its an NSString?, while nss which is a non optional NSString doesn't have its value displayed.

我认为这可能是由于它是可选的,但它并不那么简单,因为查看显示为“可选 NSString”的 onss 的显示,可以查看它和它的 NSString?,而 nss 是非可选 NSString 不显示其值。

Here's their declarations:

以下是他们的声明:

var nss:NSString = "NSString"
var ss = "Swift string"
var onss:NSString? = "Optional NSString"

So when debugging with Xcode how can the values of mdn and nss be viewed, and preferably be made to be displayed automatically without having to use the console?

那么在使用 Xcode 进行调试时,如何查看 mdn 和 nss 的值,并且最好在无需使用控制台的情况下自动显示?

回答by Keenle

Xcode 6 beta 4 shows values of variables of NSStringand NSString?types:

Xcode 6 beta 4 显示变量的值NSStringNSString?类型:

enter image description here

在此处输入图片说明

Nevertheless if you may need to see details for some other type even from some third-party framework that you cannot alter then you can implement debugQuickLookObjectmethod and return custom description. In case of third-party lib you should wrap it in extension. For NSStringit will be:

然而,如果您可能需要查看其他类型的详细信息,即使是来自某些您无法更改的第三方框架,那么您可以实现debugQuickLookObject方法并返回自定义描述。如果是第三方库,您应该将其包装在扩展名中。因为NSString它将是:

extension NSString {
    func debugQuickLookObject() -> AnyObject {
        return self
        // return "Here is debug value: \(self)"
    }
}

To preview it, just select the item in watch window and hit spacebar:

要预览它,只需在监视窗口中选择项目并点击spacebar

enter image description here

在此处输入图片说明