SecIdentity + Force Cast Violation:应避免强制施放。 (force_cast)

时间:2017-10-13 12:16:45

标签: swift security

请不要标记重复性问题。

全部,

我正在使用NSURLAuthenticationMethodClientCertificate,其中我使用以下代码。如果我不使用swiftlint,哪个代码很好。但是当我使用swiftlint时,我收到此错误并无法解决此问题。试过很多请帮助我。发布以下代码。

    var items: CFArray?
    //let PKCS12Data = DataSourceManager.sharedInstance.serverPolicyManager?.PKCS12Data
    securityError = SecPKCS12Import(certData, options, &items)

    if securityError == errSecSuccess {
        let certItems: CFArray = items as CFArray!
        let certItemsArray: Array = certItems as Array
        let dict: AnyObject? = certItemsArray.first
        if let certEntry: Dictionary = dict as? Dictionary<String, AnyObject> {

            // grab the identity
            let identityPointer = certEntry["identity"]
            let secIdentityRef = identityPointer as!  SecIdentity
            print("\(String(describing: identityPointer))  :::: \(secIdentityRef)")
            // grab the trust
            let trustPointer: AnyObject? = certEntry["trust"]
            let trustRef: SecTrust? = trustPointer as! SecTrust
            print("\(String(describing: trustPointer))  :::: \(trustRef)")
            // grab the cert
            let chainPointer: AnyObject? = certEntry["chain"]
            identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef, trust: trustRef!, certArray:  chainPointer!)

        }

    }

我在下面的行中遭到强制违规。

let secIdentityRef = identityPointer as! SecIdentity

let trustRef: SecTrust? = trustPointer as! SecTrust

1 个答案:

答案 0 :(得分:3)

基本上,您正在做的是向下压力,这意味着您保证您的identityPointertrustPointer分别是SecIdentitySecTrust类的对象。但如果他们不是呢?你将它们作为AnyObject从字典中取出,所以通常它们可能不会转换为目标类。 Swiftlint告诉你,强制施法是一种不好的做法,并希望你避免它。

但是,在CoreFoundation类型中,您似乎无法使用条件转换as?,因此强制转换是您唯一的选择。对于这种特殊情况,您可以在代码中添加特殊注释来禁用Swiftlint规则。

let secIdentityRef = identityPointer as! SecIdentity // swiftlint:disable:this force_cast

为了安全起见,您还可以通过查看Core Foundation&#34;输入ID&#34;来检查对象的身份:

guard let identityPointer = certEntry["identity"],
    CFGetTypeID(identityPointer) == SecIdentityGetTypeID() else {
    // here you know that the cast will fail
}
let secIdentityRef = identityPointer as! SecIdentity // swiftlint:disable:this force_cast