Swift 将 UIView 扩展为 return 调用类型
Swift extend UIView to return calling type
我想扩展基础 class (UIView),我在该对象上工作,return 具有正确类型的调用对象
extension UIView {
func withCleanBg() -> UIView {
self.backgroundColor = .clear
return self;
}
}
例如,如果我调用 let btn:UIButton = UIButton().withCleanBg()
,我希望 btn
在调用扩展后保留 UIButton 而不是 UpCasted。
我希望它能像这样链接函数调用
UIButton().withCleanBg().withFillInParent()
等等
Return Self
作为类型:
func withCleanBg() -> Self {
您可以 return Self
并使用 @discardableResult
属性,因此无需关心 return。有关 @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"
我想扩展基础 class (UIView),我在该对象上工作,return 具有正确类型的调用对象
extension UIView {
func withCleanBg() -> UIView {
self.backgroundColor = .clear
return self;
}
}
例如,如果我调用 let btn:UIButton = UIButton().withCleanBg()
,我希望 btn
在调用扩展后保留 UIButton 而不是 UpCasted。
我希望它能像这样链接函数调用
UIButton().withCleanBg().withFillInParent()
等等
Return Self
作为类型:
func withCleanBg() -> Self {
您可以 return Self
并使用 @discardableResult
属性,因此无需关心 return。有关 @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"