我想要扩展基类(UIView),我在基类中处理该对象并返回具有正确类型的调用对象
extension UIView {
func withCleanBg() -> UIView {
self.backgroundColor = .clear
return self;
}
}例如,如果我调用let btn:UIButton = UIButton().withCleanBg(),我希望btn在调用扩展后保持UIButton,而不是获取UpCasted。
我希望它能链接函数调用,如UIButton().withCleanBg().withFillInParent()等
发布于 2021-05-26 05:04:40
返回Self作为类型:
func withCleanBg() -> Self {发布于 2021-05-26 12:30:33
您可以返回Self并使用@discardableResult属性,因此不需要关心返回。有关@discardableResult的更多信息
extension UIView {
@discardableResult
func withCleanBg() -> Self {
self.backgroundColor = .clear
return self
}
@discardableResult
func withThemeCorner() -> Self {
self.layer.cornerRadius = 10
return self
}
@discardableResult
func withFillInParent() -> Self {
// Do your code here
return self
}
}示例:
UIButton().withCleanBg().withFillInParent() // Now this will not give warning like "Result of call to 'withFillInParent()' is unused"https://stackoverflow.com/questions/67695542
复制相似问题