相关疑难解决方法(0)

如何在Swift中打印变量的类型或类?

有没有办法在swift中打印变量的运行时类型?例如:

var now = NSDate()
var soon = now.dateByAddingTimeInterval(5.0)

println("\(now.dynamicType)") 
// Prints "(Metatype)"

println("\(now.dynamicType.description()")
// Prints "__NSDate" since objective-c Class objects have a "description" selector

println("\(soon.dynamicType.description()")
// Compile-time error since ImplicitlyUnwrappedOptional<NSDate> has no "description" method
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我正在寻找一种方法来显示变量"很快"是类型ImplicitlyUnwrappedOptional<NSDate>,或至少NSDate!.

types swift

325
推荐指数
16
解决办法
20万
查看次数

使用反射的属性类型或类

我想知道是否可以确定Objects属性的类或基本类型.获取所有属性名称和值非常简单.所以回答

那么有什么方法可以获得属性类类型,而属性没有值或零值?

示例代码

@interface MyObject : NSObject
@property (nonatomic, copy) NSString *aString;
@property (nonatomic, copy) NSDate *aDate;
@property                   NSInteger aPrimitive;
@end

@implementation MyObject
@synthesize aString;
@synthesize aDate;
@synthesize aPrimitive;

- (void)getTheTypesOfMyProperties {
    unsigned int count;
    objc_property_t* props = class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = props[i];

        // Here I can easy get the name or value
        const char * name = property_getName(property);

        // But is there any magic function that …
Run Code Online (Sandbox Code Playgroud)

reflection introspection objective-c deserialization

13
推荐指数
1
解决办法
8107
查看次数