xcode ios swift 检查对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31506905/
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 07:31:05  来源:igfitidea点击:

Check Type of Object ios swift

xcodeswift

提问by nhgrif

How do I check the type of object my variable is in ios swift?

如何检查我的变量在 ios swift 中的对象类型?

For Example

例如

let test= ["Chicago", "New York", "Oregon", "Tampa"]

is test NSArray? NSMutableArray? NSString?

是测试 NSArray?NSMutableArray?NSString?

I'm used to visual studio using an immediate window, can this be in debug mode in Xcode?

我习惯于使用即时窗口的 Visual Studio,这可以在 Xcode 中处于调试模式吗?

回答by nhgrif

There are several methods for determine an object's type at debug or compile time.

有几种方法可以在调试或编译时确定对象的类型。



If the variable's type is explicitly declared, just look for it:

如果显式声明了变量的类型,只需查找它:

let test: [String] = ["Chicago", "New York", "Oregon", "Tampa"]

Here, testis clearly marked as a [String](a Swift array of Strings).

在这里,test被清楚地标记为 a [String](一个Strings的 Swift 数组)。



If the variable's type is implicitly inferred, we can get some information by ? Option+clicking.

如果变量的类型是隐式推断的,我们可以通过? Option+click获取一些信息。

let test = ["Chicago", "New York", "Oregon", "Tampa"]

enter image description here

在此处输入图片说明

Here, we can see test's type is [String].

在这里,我们可以看到test的类型是[String]



We can print the object's type using dynamicType:

我们可以使用dynamicType以下方法打印对象的类型:

let test = ["Chicago", "New York", "Oregon", "Tampa"]

println(test.dynamicType)

Prints:

印刷:

Swift.Array<Swift.String>


We can also see our variable in the variable's view:

我们还可以在变量视图中看到我们的变量:

enter image description here

在此处输入图片说明

Here, we can see the variable's type clearly in the parenthesis: [String]

在这里,我们可以在括号中清楚地看到变量的类型:[String]



Also, at a break point, we can ask the debugger about the variable:

此外,在断点处,我们可以向调试器询问变量:

(lldb) po test
["Chicago", "New York", "Oregon", "Tampa"]

(lldb) po test.dynamicType
Swift.Array<Swift.String>

回答by Shamas S - Reinstate Monica

You can use isin Swift.

您可以is在 Swift 中使用。

if test is NSArray {
  println("is NSArray")
}

回答by mrabins

type(of:)

Which Returns the dynamic type of a value.

返回值的动态类型。

func foo<T>(x: T) -> T.Type {
  return type(of: x)
}