w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Test if variable is declared in a class in Swift

Right now there isn't a pure Swift way of doing this (reflect isn't enough), maybe objc runtime methods can help. Using class_copyIvarList:

func hasProperty (obj: AnyObject, property: String) -> Bool {

    var count: UInt32 = 0
    var ivars: UnsafeMutablePointer<Ivar> =
class_copyIvarList(obj.dynamicType, &count)

    for i in 0..<count {
        let name = NSString(CString: ivar_getName(ivars[Int(i)]), encoding:
NSUTF8StringEncoding)
        if name == property {
            return true
        }
    }

    return false
}

Usage:

public class R {
    private var aVar = "Hi"
    private var anotherVar: Int = 0
}

hasProperty(R(), "anotherVar") // outputs true




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.