iosswift3swift2dynamictype

Dynamic Type in Swift 3


I've migrated my swift version from 2.3 to 3 and it converted some code automatically, below is the case on which i'm getting crash i've tried some options but in vain,

swift 2.3:Works fine

public func huntSuperviewWithClassName(className: String) -> UIView?
{
    var foundView: UIView? = nil

    var currentVeiw:UIView? = self

    while currentVeiw?.superview != nil{
        if let classString = String.fromCString(class_getName(currentVeiw?.dynamicType)){

            if let classNameWithoutPackage = classString.componentsSeparatedByString(".").last{
                print(classNameWithoutPackage)
                if classNameWithoutPackage == className{
                    foundView = currentVeiw
                    break
                }
            }
        }
        currentVeiw = currentVeiw?.superview
    }

    return foundView
}

}

swift 3:Not fine

  if let classString = String(validatingUTF8: class_getName(type(of:currentVeiw) as! AnyClass)) {

Tried this line too:

  if let classString = String(describing: class_getName(type(of: currentVeiw) as! AnyClass)){

but it doesn't work..

please guide me how to correct this line according to swift 3:

 if let classString = String.fromCString(class_getName(currentVeiw?.dynamicType)){

Solution

  • The compiler is telling you that you can't use an if let because it's totally unnecessary. You don't have any optionals to unwrap.if let is used exclusively to unwrap optionals.

    public func huntSuperviewWithClassName(className: String) -> UIView?
    {
        var foundView: UIView? = nil
    
        var currentVeiw:UIView? = self
    
        while currentVeiw?.superview != nil{
    
                let classString = NSStringFromClass((currentVeiw?.classForCoder)!)
    
                if let classNameWithoutPackage = classString.components(separatedBy:".").last{
                    print(classNameWithoutPackage)
                    if classNameWithoutPackage == className{
                        foundView = currentVeiw
                        break
                    }
                }
            }
            currentVeiw = currentVeiw?.superview
        }
    
        return foundView
    }
    

    works Fine!