无法通过扩展将初始化程序添加到Swift中的结构

时间:2019-01-13 15:19:59

标签: swift struct initializer

我试图在Struct Rect扩展名中添加以“ centre”和“ size”作为参数的便捷初始化程序,但是它对于以“ origin”和“ size”为参数的初始化器显示出错误要求。 RunSwift编译器中显示错误:

/consumers/{consumer_id}

代码如下:

/var/folders/_x/3ll0j9g13tqfr6lj42jh8qjc0000gn/T/9799.swift:19:17: error: incorrect argument label in call (have 'centre:size:', expected 'origin:size:')
let cRect = Rect(centre: Point(x: 2.5, y: 2.5), size: Size(width: 5.0, height: 5.0))
                ^~~~~~~
                 origin

请帮助。我被困住了。

1 个答案:

答案 0 :(得分:0)

只需将扩展部分移到要调用init方法的代码之前(我假设您正在使用Playground)

extension Rect {
  init(centre: Point, size: Size){
    let originX = centre.x - (size.width)/2
    let originY = centre.y - (size.height)/2
    self.init(origin: Point(x: originX, y: originY), size : size)
  }
}

let cRect = Rect(centre: Point(x: 2.5, y: 2.5), size: Size(width: 5.0, height: 5.0))
print("cRect origin is = \(cRect.origin)")