How can make Getter or Setter Property in Class in Swift

时间:2019-04-08 13:21:19

标签: ios swift

I want to set my property just getter that's means the user can just get not setting into property

this Apple Library Code Id like this code


 open var imageView: UIImageView? { get } // default is nil.  image view will be created if necessary.


    @available(iOS 3.0, *)
    open var textLabel: UILabel? { get } // default is nil.  label will be created if necessary.

    @available(iOS 3.0, *)
    open var detailTextLabel: UILabel? { get } // default is nil.  label will be created if necessary (and the current style supports a detail label).


    // If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.
    open var contentView: UIView { get }


3 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,这就是你想要的:

private(set) var foo: Int = 0

现在只有getter是公开的

答案 1 :(得分:0)

if you make it a constant property no one will be able to modify it :

var someProperty = 10
let constantProperty = 10

someProperty = 15
//all good, var has setter and getter
constantProperty = 15
//error : Cannot assign to value: 'constantProperty' is a 'let' constant because let has only getter

答案 2 :(得分:0)

您可以按照以下方式使用

class myClass{
private var _myInt: Int = 10
public var myVar: Int {
    get {
        return _myInt
    }
}
public func changeint(_ newval: Int) {
    _myInt = newval
}
}

并简单地使用它:

var newclass = myClass()

print("\(newclass.myVar)")
newclass.changeint(12)
print("\(newclass.myVar)")