Swift中没有默认(T)吗? [英] Is there no default(T) in Swift?

查看:127
本文介绍了Swift中没有默认(T)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我到目前为止所得到的结果:

  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&&行<行&& >列> = 0&&列<列
}

下标(行:Int,列:Int) - > $ {
$ {
} $ {
返回网格[(row * columns)+ column]
} assert(indexIsValidForRow(row,column:column),Index out of range
set {
assert(indexIsValidForRow(row,column:column),Index out of range)
grid [(row * columns)+ column] = newValue
}






请注意,我必须通过重复值:T 给构造函数。



在C#中,我只是使用 default(T),其中 0 为数字, false 为布尔值, null 作为参考类型。我知道Swift不允许在非可选类型中使用 nil ,但是我仍然很好奇,如果传递一个显式参数是唯一的方法,或者如果我有 some 相当于 default(T) there。

解决方案

<没有。 Swift强迫你指定默认值,就像你处理变量和字段一样。 Swift具有默认值的唯一情况是可选类型,它是 nil Optional.None ) 。


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.

解决方案

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

这篇关于Swift中没有默认(T)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆