财产获取者和安置者 [英] Property getters and setters

查看:68
本文介绍了财产获取者和安置者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过这个简单的类,我得到了编译器 warning


试图修改/访问 x 在它自己的设置器/获取器中


,当我这样使用时:

  var p:point = Point()
px = 12

我得到一个EXC_BAD_ACCESS。

  class Point {

var x:Int {
set {
x = newValue * 2 //错误
}
get {
return x / 2 //错误
}
}
// ... ...
}


解决方案

Setter和Getters应用于计算的属性;这样的属性在实例中没有存储-来自getter的值应从其他实例属性中计算出来。在您的情况下,没有要分配的 x 。支持ivars。您不能-您需要某事来备份计算出的属性。试试这个:

  class Point {
private var _x:Int = 0 // _x-> backingX
var x:Int {
set {_x = 2 * newValue}
get {return _x / 2}
}
}

具体地说,在Swift REPL中:

  15> var pt = Point()
pt:Point = {
_x = 0
}
16> pt.x = 10
17> pt
$ R3:点= {
_x = 20
}
18> pt.x
$ R4:Int = 10


With this simple class I am getting the compiler warning

Attempting to modify/access x within its own setter/getter

and when I use it like this:

var p: point = Point()
p.x = 12

I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?

class Point {

    var x: Int {
        set {
            x = newValue * 2 //Error
        }
        get {
            return x / 2 //Error
        }
    }
    // ...
}

解决方案

Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.

Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:

class Point {
  private var _x: Int = 0             // _x -> backingX
  var x: Int {
    set { _x = 2 * newValue }
    get { return _x / 2 }
  }
}

Specifically, in the Swift REPL:

 15> var pt = Point()
pt: Point = {
  _x = 0
}
 16> pt.x = 10
 17> pt
$R3: Point = {
  _x = 20
}
 18> pt.x
$R4: Int = 10

这篇关于财产获取者和安置者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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