最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Swift中如何获得一个变量的类型type

Swift crifan 3180浏览 0评论
[背景]
折腾:
期间,去看:
The Swift Programming Language (Swift 2.1): Type Casting
然后想要知道:
Swift中,对于那个数组变量library,打印出来的类型,是否是:[MediaItem]
[折腾过程]
1.去创建一个Xcode的PlayGround,粘贴对应代码:
xcode file new playground
TestSwiftVarType
new ios playground TestSwiftVarType然后把代码粘贴到Playground中:
paste mediaitem code into playground
2.然后就要去搞清楚,到底如何才能打印出来Swift中变量的类型
搜:
swift print variable type
参考:
3.在输入代码期间,动态提示中,的确倒是可以看到
library type is MediaItem
library的类型是[MediaItem]
4.试了Type和dynamicType都不行。
不过后来再去试试:
print(toString(library.dynamicType))
不行,提示要换成:
Fixit Replace “toString” with “String”
notice Fixit Replace toString with String
最终是用:
print(String(library.dynamicType))
输出是:
“Array<MediaItem>\n”
5.再去参考;
How do you find out the type of an object (in Swift)? – Stack Overflow
好像对于dynamicType,还可以有其他属性或方法的,比如className(),所以去试试:
结果此处的iOS 9.0,Xcode 7.0.1中,是没有的:
ios 9 Xcode 7 no className
6.会不会是:
只有class才可以有上面两个className和printClassName?
去试试:
let someMovie = Movie(name: "xxx", director:"yyy")
print(someMovie.dynamicType.className())
print(someMovie.dynamicType.printClassName())
结果都没有:
Playground execution failed: /var/folders/46/2hjxz38n22n3ypp_5f6_p__00000gn/T/./lldb/3315/playground45.swift:42:17: error: type ‘Movie’ has no member ‘className’
error type Movie has no member className
error: type ‘Movie’ has no member ‘printClassName’
然后在:
看到评论了:
the printClassName() method is just an example method they created in one of the samples in the docs, it is not an API call you can access.
7.再去试试人家的代码:
class PureSwiftClass { }

var myvar0 = NSString() // Objective-C class
var myvar1 = PureSwiftClass()
var myvar2 = 42
var myvar3 = "Hans"

print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)")
print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)")
print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)")
print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)")

print( "String(Int.self) -> \(Int.self)")
print( "String((Int?).self -> \((Int?).self)")
print( "String(NSString.self) -> \(NSString.self)")
print( "String(Array<String>.self) -> \(Array<String>.self)")
结果是:
String(myvar0.dynamicType) -> __NSCFConstantString
String(myvar1.dynamicType) -> PureSwiftClass
String(myvar2.dynamicType) -> Int
String(myvar3.dynamicType) -> String
String(Int.self) -> Int
String((Int?).self -> Optional<Int>
String(NSString.self) -> NSString
String(Array<String>.self) -> Array<String>
如图:
try other get type code result
[总结]
Swift中,想要获得,打印出,一个变量的类型,可以用:
print(String(xxx.dynamicType))
即可。

转载请注明:在路上 » [已解决]Swift中如何获得一个变量的类型type

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
86 queries in 0.172 seconds, using 22.16MB memory