Swift不允许在extension中直接添加「存储属性」。但是在我们的实际开发中经常会用到使用extension来给已经创建好的类添加新的「存储属性」。例如,给UIView类添加一个y属性来区别不同UIView实例。
如果直接在UIView的extension中添加,编译器会报Extensions must not contain stored properties。如下图:

既然不能直接定义存储属性identifier,我们可以使用关联属性来实现想要的功能。代码如下:

Swift不允许在extension中直接添加「存储属性」。但是在我们的实际开发中经常会用到使用extension来给已经创建好的类添加新的「存储属性」。例如,给UIView类添加一个y属性来区别不同UIView实例。
如果直接在UIView的extension中添加,编译器会报Extensions must not contain stored properties。如下图:
既然不能直接定义存储属性identifier,我们可以使用关联属性来实现想要的功能。代码如下:
本文标题:swift-类目添加属性
本文链接:https://www.haomeiwen.com/subject/sadkqltx.html
网友评论