Dan Abramov Dan Abramov - 2 months ago 6
Swift Question

Is there no default(T) in Swift?

I'm trying to port the Matrix example from Swift book to be generic.

Here's what I got so far:

struct Matrix<T> {
let rows: Int, columns: Int
var grid: T[]

init(rows: Int, columns: Int, repeatedValue: T) {
self.rows = rows
self.columns = columns

grid = Array(count: rows * columns, repeatedValue: repeatedValue)
}

func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}

subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}


Note that I had to pass
repeatedValue: T
to the constructor.

In C#, I would have just used
default(T)
which would be
0
for numbers,
false
for booleans and
null
for reference types. I understand that Swift doesn't allow
nil
on non-optional types but I'm still curious if passing an explicit parameter is the only way, or if I there is some equivalent of
default(T)
there.

Answer

There isn't. Swift forces you to specify the default value, just like then you handle variables and fields. The only case where Swift has a concept of default value is for optional types, where it's nil (Optional.None).

Comments