-1

I have a dict of [String: NSNumber] in my Card class called data (original!). There is an array of these [Card]s in my document called deck. I have deck bound to an NSTableView, which is displaying everything wonderfully.

Now I'm trying to write the setObjectValue delegate method:

func tableView(tableView: NSTableView, setObjectValue anObject: AnyObject?, forTableColumn tableColumn: NSTableColumn?, row rowIndex: Int) {
    print("set got called on row " + String(rowIndex) + " and column " + tableColumn!.identifier + " with " + String(anObject))
    guard var d = deck?.geometryCards[rowIndex].data else { return }
    guard let i = tableColumn?.identifier where i.length > 0 else { return }
    let key = i.substring(0, length:(i.length - "Column".length))
    d[key] = anObject
}

That doesn't work because the value in the dict is an NSNumber, but the value coming back from the table is an AnyObject. Now normally in Swift when I run into casting issues, this would work every time:

d[key] = NSNumber(anObject)

But that doesn't work here, because you need to specify the type, and in this case I don't know what it is - it could be Int or Double. What's the trick here?

Community
  • 1
  • 1
Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98
  • How can and Int or Double be passed into anObject if Int and Double are not objects? – tktsubota Dec 19 '15 at 20:09
  • I'm sorry, I don't understand what you mean. The original dictionary, data, contains a list of Int and Double, which you can put into a dict of NSNumber. – Maury Markowitz Dec 19 '15 at 20:12
  • So the dictionary, data, is a [String : NSNumber] dictionary in which the NSNumber represents either an Int or a Double, correct? – tktsubota Dec 19 '15 at 20:30

1 Answers1

2

If you know that anObject is either an Int or a Double, then it has to already be an NSNumber because that is the only way to store Int and Double as an AnyObject (since they are not objects):

The safe way to cast it would be with a conditional cast as? and optional binding:

if let number = anObject as? NSNumber {
    d[key] = number
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Ok, I get it, and understand Troy's question above. So then, are all NSNumbers the same? Or is a NSNumber from an Int different in some way than an NSNumber from a double? – Maury Markowitz Dec 20 '15 at 14:04
  • All `NSNumbers` are the same. You can initialize an `NSNumber` with a `double` and then ask for its `integerValue` and it will give you one (by truncating). – vacawama Dec 20 '15 at 14:19
  • Control-click on `NSNumber` in your code or a Playground for a big explanation. – vacawama Dec 20 '15 at 14:20