Is there no default(T) in Swift?

前端 未结 3 2234
感情败类
感情败类 2021-02-18 22:40

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

Here\'s what I got so far:

struct Matrix {
    let rows: Int, columns: Int         


        
3条回答
  •  生来不讨喜
    2021-02-18 23:14

    An iffy 'YES'. You can use protocol constraints to specify the requirement that your generic class or function will only work with types that implement the default init function (parameter-less). The ramifications of this will most likely be bad (it doesn't work the way you think it does), but it is the closest thing to what you were asking for, probably closer than the 'NO' answer.

    For me I found this personally to be helpful during development of a new generic class, and then eventually I remove the constraint and fix the remaining issues. Requiring only types that can take on a default value will limit the usefulness of your generic data type.

    public protocol Defaultable
    {
      init()
    }
    
    struct Matrix
    {
      let rows: Int
      let columns: Int
      var grid: [Type]
    
      init(rows: Int, columns: Int)
      {
        self.rows = rows
        self.columns = columns
    
        grid = Array(count: rows * columns, repeatedValue: Type() )
      }
    }
    

提交回复
热议问题