斯威夫特编译器警告说,重写一个getter
时,我必须用自己我有我的类此属性:斯威夫特编译器警告说,重写一个getter
var currentPage: Int
{
set
{
self.currentPage = min(max(0, newValue), self.numberOfPages - 1)
self.setNeedsDisplay()
}
get
{
return self.currentPage
}
}
我知道这个问题是在弄,但如果我只有:
get
{
return currentPage
}
编译器会给我一个警告,并建议我在前面添加“self”。
基本上,我想从Objective-C的重构这个代码:
@interface MyClass
@property (nonatomic, assign) NSInteger currentPage;
@end
@implementation MyClass
- (void)setCurrentPage:(NSInteger)pageNumber
{
_currentPage = min(max(0, pageNumber), self.numberOfPages - 1);
[self setNeedsDisplay];
}
- (NSInteger)currentPage
{
return _currentPage;
}
@end
您需要同时override
关键字添加到您的财产申报,然后访问当你的父类的存储特性使用super
:
class MyPageControl: UIPageControl {
override var currentPage: Int {
get { return super.currentPage }
set {
super.currentPage = min(max(0, newValue), self.numberOfPages - 1)
self.setNeedsDisplay()
}
}
}
(是不是currentPage
总是要结束了0与逻辑?)
如果你实际上并没有首要currentPage
,你想使用一个didSet
处理程序:
class MyPageControl: UIView {
var numberOfPages = 6
var currentPage: Int = 0 {
didSet {
self.currentPage = min(max(0, self.currentPage), self.numberOfPages - 1)
self.setNeedsDisplay()
}
}
}
我不确定OP是否属于子类;听起来更像是他试图实现通常使用自定义getter/setter中的'_currentPage'的Objective-C惯用法。 – 2014-11-08 16:50:23
谢谢,但重写给我编译时错误,因为currentPage是我在当前类中声明的变量。我只想创建一个像这样的变量/属性:“var currentPage:Int”并简单地覆盖setter,getter应该具有默认行为,那么哪种方法是最好的/最简单的方法呢? – ppalancica 2014-11-08 16:51:29
@ppalancica'willSet'和'didSet'观察者是在这里做你想做的事的方法。有关更多信息,请参阅我的更新和[文档](https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Properties.html)。 – 2014-11-08 17:45:35
如果您正在覆盖从基类currentpage
,你应该使用super
,不self
。
你有什么问题? – 2014-11-08 16:34:09
你打算在这里做什么?因为他们自称自己,所以你的制定者和你的吸气者都会造成无限循环。 – 2014-11-08 16:34:32
谢谢,伙计们!问题在于由于很多自我调用而导致无限循环。我意识到这一点,我知道如何在Objective-C中做到这一点,但在Swift中我不确定。我只想简单地返回currentPage的值。 – ppalancica 2014-11-08 16:45:21