从swift中的名称中获取属性的类型/类

前端之家收集整理的这篇文章主要介绍了从swift中的名称中获取属性的类型/类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
让我们说我有这个课程:
class Node {
    var value: String
    var children: [Node]?
}

如果我有一个属性名称(例如“children”),我该如何获得它的类型? (在这种情况下[节点]?)

我想像下面这样的全局函数可以解决我的需求:

func typeOfPropertyWithName(name: String,ofClass: AnyClass) -> AnyClass? {
    //???
}

// Example usage:
var arrayOfNodesClass = typeOfPropertyWithName("children",Node.self)
Swift 2(注:反射改变了):
import Foundation

enum PropertyTypes:String
{
    case OptionalInt = "Optional<Int>"
    case Int = "Int"
    case OptionalString = "Optional<String>"
    case String = "String"
    //...
}

extension NSObject{
    //returns the property type
    func getTypeOfProperty(name:String)->String?
    {
        let type: Mirror = Mirror(reflecting:self)

        for child in type.children {
            if child.label! == name
            {
                return String(child.value.dynamicType)
            }
        }
        return nil
    }

    //Property Type Comparison
    func propertyIsOfType(propertyName:String,type:PropertyTypes)->Bool
    {
        if getTypeOfProperty(propertyName) == type.rawValue
        {
            return true
        }

        return false
    }
}

自定义类:

class Person : NSObject {
    var id:Int?
    var name : String?
    var email : String?
    var password : String?
    var child:Person?
}

获取“子”属性的类型:

let person = Person()
let type = person.getTypeOfProperty("child")
print(type!) //-> Optional<Person>

物业类型检查:

print( person.propertyIsOfType("email",type: PropertyTypes.OptionalInt) ) //--> false
print( person.propertyIsOfType("email",type: PropertyTypes.OptionalString) //--> true

要么

if person.propertyIsOfType("email",type: PropertyTypes.OptionalString)
{
    //true -> do something
}
else
{
    //false -> do something
}

猜你在找的Swift相关文章