Swift - 将Int64转换为AnyObject for NSMutableArray

时间:2014-12-04 23:04:10

标签: swift casting nsmutablearray int64

您好我有一个NSMutableArray,我试试这个:

var ma = NSMutableArray()
let number:Int64 = 8345834344
ma.addObject(number)// Error "Type Int64 does not conform to protocol AnyObject"

如何将Int64变量添加到NSMutableArray()?

2 个答案:

答案 0 :(得分:10)

您正在使用Foundation数组(NSMutableArray),因此您应该使用Foundation数字对象:

ma.addObject(NSNumber(longLong:number))

你也可以使用原生的swift数组:

var ma = [Int64]()
ma.append(number)

答案 1 :(得分:9)

像Swift一样,这是在Swift中实现的。

所以你可以这样做(或者你想要的类型的等价物),它可以神奇地使用语言期望AnyObject的Int64:

extension Int64 : _ObjectiveCBridgeable
{
    public init(_ number: NSNumber)
    {
        self.init(number.longLongValue)
    }

    public func _bridgeToObjectiveC() -> NSNumber
    {
        return NSNumber(longLong: self)
    }

    public static func _getObjectiveCType() -> Any.Type
    {
        return NSNumber.self
    }

    public static func _isBridgedToObjectiveC() -> Bool
    {
        return true
    }

    public static func _forceBridgeFromObjectiveC(source: NSNumber, inout result: Int64?)
    {
        result = source.longLongValue
    }

    public static func _conditionallyBridgeFromObjectiveC(source: NSNumber, inout result: Int64?) -> Bool
    {
        result = source.longLongValue
        return true
    }
}