Swift - Cast Int64 to AnyObject for NSMutableArray
Asked Answered
H

2

6

Hi I have a NSMutableArray and I try this:

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

How to add Int64 variable to NSMutableArray() ?

Hypertensive answered 4/12, 2014 at 23:4 Comment(0)
D
10

You are using a Foundation array (NSMutableArray), so you should use a Foundation number object:

ma.addObject(NSNumber(longLong:number))

You could also use a native swift array:

var ma = [Int64]()
ma.append(number)
Dymoke answered 4/12, 2014 at 23:8 Comment(3)
Thanks. I want NSMutableArray() to use .objectAtIndex :)Hypertensive
No, I just don't know how to find index in swift array :)Hypertensive
Swift arrays have their own index finding mechanism: let arr = ["a","b","c"] let indexOfA = arr.indexOf("a")Duplet
S
9

Like so much of Swift, this is implemented in Swift.

So you can do this (or the equivalent for the types you want) which will magically make it possible to use an Int64 where the language expects an AnyObject:

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
    }
}
Steamtight answered 4/4, 2016 at 11:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.