简体   繁体   English

在Swift中声明和使用自定义属性

[英]Declaring and using custom attributes in Swift

I would like to be able to annotate my types and methods with meta-data and read those at runtime. 我希望能够用元数据注释我的类型和方法,并在运行时读取它们。

The language reference explains how to declare attribute usages , but is it actually possible to declare your own attributes? 语言参考说明了如何声明属性用法 ,但是实际上可以声明自己的属性吗?

Reading would require some kind of reflection mechanism, which I was not able to find in the reference at all, so the second part of the question probably is - is there reflection possible. 阅读将需要某种反射机制,我根本无法在参考文献中找到这种反射机制,因此问题的第二部分可能是-是否存在反射的可能。 If these features are not available in Swift, can they be done with Objective-C code (but on Swift instances and types)? 如果这些功能在Swift中不可用,是否可以用Objective-C代码完成(但在Swift实例和类型上)?

A relatively unrelated note: The decision of what has been modelled as an attribute and what has been added to the core syntax strikes me as pretty arbitrary. 相对不相关的注释:关于将什么建模为属性以及将哪些内容添加到核心语法的决定让我感到非常武断。 It feels like two different teams worked on the syntax and on some attributes. 感觉像是两个不同的团队在语法和某些属性上工作。 Eg they put weak and unowned into the language as modifiers, but made @final and @lazy attributes. 例如,他们把weakunowned到语言作为修饰,但做@final@lazy属性。 I believe that once they actually add access modifiers, they will probably be attributes likes final . 我相信,一旦他们实际上添加了访问修饰符,它们可能就是诸如final属性。 Is all of this somehow related to Objective-C interoperability? 所有这些都与Objective-C的互操作性相关吗?

If we take the iBook as definitive, there appears to be no developer-facing way of creating arbitrary new attributes in the way you can in Java and .NET. 如果我们将iBook作为权威,那么似乎就没有像Java和.NET那样面向开发人员的创建任意新属性的方法。 I hope this feature comes in later, but for now, it looks like we're out of luck. 我希望此功能稍后发布,但就目前而言,我们似乎还不走运。 If you care about this feature, you should file an enhancement request with Apple (Component: Swift Version: X ) 如果您关心此功能,则应向Apple提出增强请求 (组件: Swift版本: X

FWIW, there's really not a way to do this in Objective-C either. FWIW,在Objective-C中也确实没有做到这一点的方法。

You can now do something like this! 您现在可以执行类似的操作! Check out "Property Wrappers" - https://docs.swift.org/swift-book/LanguageGuide/Properties.html 请查看“属性包装器” - https://docs.swift.org/swift-book/LanguageGuide/Properties.html

Here's an example from that page: 这是该页面上的示例:

@propertyWrapper
struct TwelveOrLess {
    private var number = 0
    var wrappedValue: Int {
        get { return number }
        set { number = min(newValue, 12) }
    }
}


struct SmallRectangle {
    @TwelveOrLess var height: Int
    @TwelveOrLess var width: Int
}

var rectangle = SmallRectangle()
print(rectangle.height)
// Prints "0"

rectangle.height = 10
print(rectangle.height)
// Prints "10"

rectangle.height = 24
print(rectangle.height)
// Prints "12"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM