Swift 扩展异常执行被中断,原因:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Swift Extension exception Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

我尝试对 NSDate 进行扩展。我想要的是一个标志,指示以后是否必须删除 NSDate

所以我在操场上试过了

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"



extension NSDate {
    private struct RemovalInformation {
        static var removed: Bool = false
    }
    var removed: Bool {
        get {
            return (objc_getAssociatedObject(self, &RemovalInformation.removed) as! Bool)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

let date = NSDate()
print( "The Date is: \(date)")

if(date.removed == true) {
    print ("removed")
}

但是第 if(date.removed == true) 行产生了一个错误,我不知道如何处理:"EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

objc_getAssociatedObject returns nil 如果没有关联对象 到 NSDate,然后强制转换 as! Bool 崩溃。 (如果已设置关联对象,它也会崩溃,但它的 值不可转换为 Bool。)

您可以将 属性 设为可选:

var removed: Bool? {
    get {
        return objc_getAssociatedObject(self, &RemovalInformation.removed) as? Bool
    }
    set(newValue) {
        objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

或提供默认值,例如使用零合并运算符 ??:

var removed: Bool {
    get {
        return objc_getAssociatedObject(self, &RemovalInformation.removed) as? Bool ?? false
    }
    set(newValue) {
        objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

注意&RemovalInformation.removed只是作为内存地址 唯一标识关联对象。那个的内容 static 属性 和它的类型无关,根本没有使用。特别是,对象关联不是 "initialized" 与 属性 的值。