swift2 Swift 3中的动态类型

bq3bfh9z  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(233)

我已经将我的swift版本从2.3迁移到3,它自动转换了一些代码,下面是我遇到崩溃的情况,我尝试了一些选项,但都是徒劳的,
swift 2.3:* 工作正常 *

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
}

}
雨燕3:不好

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

也试过这一行:

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

但它不起作用。
请指导我如何根据swift3:

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

pgccezyw1#

编译器告诉你不能使用if let,因为它是完全不必要的。你没有任何可选择的解包。if let专门用于解包可选择的。

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
}

工作正常!

bttbmeg0

bttbmeg02#

if let classString = String(describing: currentVeiw.self) 
{
}
gc0ot86w

gc0ot86w3#

只需执行以下操作:

let classString = String(describing: type(of: currentVeiw!))
voj3qocg

voj3qocg4#

请尝试以下操作:

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

相关问题