swift - 自类型作为闭包中的参数
问题描述
a 的实例是否可以UIView
调用执行闭包的方法,并在该闭包内部引用同一个实例?这是非通用版本:
import UIKit
public extension UIView {
func layout(from: (UIView) -> ()) {
from(self)
}
}
例如,当我用 UILabel 调用它时,我无法访问例如文本对齐。是否有可能在闭包内我可以参考 UILabel?我希望这样的事情会起作用:
func layout(from: (Self) -> ()) {
from(self)
}
但它不编译。有解决方法吗?这就是我要的:
let label = UILabel(frame: .zero)
label.layout { $0.textAlignment = .natural } // Currenly not working, since $0 = UIView.
解决方案
不同的方法:具有关联类型的协议扩展。
protocol Layout {
associatedtype View : UIView = Self
func layout(from: (View) -> ())
}
extension Layout where Self : UIView {
func layout(from: (Self) -> ()) {
from(self)
}
}
extension UIView : Layout {}
let label = UILabel(frame: .zero)
label.layout { $0.textAlignment = .natural }
推荐阅读
- sql - 如何在 SQL 中根据文本数据生成计数
- haskell - haskell 导入 Data.List 模块失败
- ionic-framework - 如何在 Ionic 4/5 中拖动元素
- embedded - 使用示波器测量 USB 电缆的功率
- python - 如何使用 OpenCV 使图像上的文本清晰锐利
- elasticsearch - 如何按 java 枚举搜索
- python - 将数据从树视图保存到 csv 文件 tkinter python
- bash - bash 环境变量列表末尾的意外条目
- r - 如何将实数与小标题中的列进行比较?
- python - 如何知道元素是否在 iframe 中?