让我们说我有这个课程:
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 }