Dan Abramov Dan Abramov - 1 year ago 46
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
which would be
for numbers,
for booleans and
for reference types. I understand that Swift doesn't allow
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

Answer Source

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).