2

New Swift enthusiast here! I'm following Rey Wenderlich's Candy Crush tutorial and get an error when multiplying two Int values. I know Swift is strictly typed so would be the reason? Am I not allowed to do this in Swift? Note the error comments where I'm having trouble. Any help in the right direction is greatly appreciated!

class Array2D<T> {
  let columns: Int
  let rows: Int
  let array: Array<T>

  init(columns: Int, rows: Int) {
    self.columns = columns
    self.rows = rows
    array = Array<T?>(count: rows*columns, repeatedValue: nil)    // ERROR: could not find an overload for '*' that accepts the supplied arguments
  }

  subscript(column: Int, row: Int) -> T? {
    get {
        return array[row*columns + column]
    }
    set {
        array[row*columns + column] = newValue   // ERROR: could not find an overload for '*' that accepts the supplied arguments
    }
  }
}
andy4thehuynh
  • 2,042
  • 3
  • 27
  • 37

1 Answers1

4

Change your array to be of type T?. In the first case, you are trying to assign array of type T? to array of type T. In the second, you are trying to assign newValue of type T? to an element of array of type T.

Changing the type of the array fixes both these things.

Roshan
  • 1,937
  • 1
  • 13
  • 25
  • You're the man Roshan. Does the `T?` mean it could be of any type? – andy4thehuynh Jul 04 '14 at 01:36
  • Nope.. ```T?``` refers to an ''optional'' of type ```T```. It basically says it can hold a value of type ```T``` or no value(```nil```). See http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift. Of course, ```T``` itself can be any type but once you fix ```T```, ```T?``` is also fixed. – Roshan Jul 04 '14 at 02:12
  • So you're saying on the first 'error' line, `count` could've been `nil` with the ``.. OR if it was set to an `Int`, then it would be fixed as an Int? – andy4thehuynh Jul 04 '14 at 02:14
  • ```init(count: Int, repeatedValue: T)``` is the method signature defined for ```Array```. In your case, ```T``` is ```T?```. Therefore ```count``` is ```Int```, not ```Int?``` which means you have to give an integer, not ```nil```. However, ```repeatedValue``` is ```T?```, so you can give a value of type ```T``` OR ```nil``` – Roshan Jul 04 '14 at 02:20
  • This is a little confusing at first, esp. if you have come from Objective-C. ```nil``` gets very special treatment in Swift. – Roshan Jul 04 '14 at 02:22
  • Okay, I'll have to check out the docs for this case. A little confusing for sure. Thanks tho! – andy4thehuynh Jul 04 '14 at 02:54