简体   繁体   English

在Swift中将nil分配给泛型可选

[英]Assigning nil to generic optionals in Swift

I've created a simple generic grid data structure in Swift as follows. 我已经在Swift中创建了一个简单的通用网格数据结构,如下所示。 Basically it creates an Array of optionals with type T? 基本上,它会创建类型为T的可选数组? and initialises the array with with nil. 并使用nil初始化数组。 But when I try to explicitly set one grid element back to nil the compiler complains with something I don't really understand. 但是,当我尝试将一个grid元素显式设置为nil时,编译器会抱怨一些我不太了解的东西。

struct Grid<T> {
    let columns: Int, rows: Int
    var grid: [T?]
    init(columns: Int, rows: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: nil)
    }

    func test() {
        grid[0] = nil
    }
}

Compiler's outcry when test() function is added: 添加test()函数时,编译器强烈要求:

Grid.swift:26:13: '@lvalue $T7' is not identical to 'T?'

The error message is misleading. 该错误信息是令人误解的。 The test() method modifies the value of a property in the structure, therefore you have to mark it as "mutating": test()方法修改结构中属性的值,因此必须将其标记为“变异”:

struct Grid<T> {
    // ...

    mutating func test() {
        grid[0] = nil
    }
}

See Modifying Value Types from Within Instance Methods in the Swift book: 请参见Swift书中的从实例方法内部修改值类型

Modifying Value Types from Within Instance Methods 从实例方法中修改值类型

Structures and enumerations are value types . 结构和枚举是值类型 By default, the properties of a value type cannot be modified from within its instance methods. 默认情况下,不能从其实例方法中修改值类型的属性。

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. 但是,如果你需要一个特定的方法修改您的结构或枚举的属性,你可以选择参加变异行为该方法。 ... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM