ios - Assigning nil to generic optionals in Swift -
i've created simple generic grid data structure in swift follows. creates array of optionals type t? , initialises array with nil. when try explicitly set 1 grid element nil compiler complains don't understand.
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 added:
grid.swift:26:13: '@lvalue $t7' not identical 't?'
the error message misleading. test()
method modifies value of property in structure, therefore have mark "mutating":
struct grid<t> { // ... mutating func test() { grid[0] = nil } }
see modifying value types within instance methods in swift book:
modifying value types within instance methods
structures , enumerations value types. default, properties of value type cannot modified within instance methods.
however, if need modify properties of structure or enumeration within particular method, can opt in mutating behavior method. ...
Comments
Post a Comment