Declaring and using custom attributes in Swift

前端 未结 2 1911
花落未央
花落未央 2020-12-17 08:47

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,

相关标签:
2条回答
  • 2020-12-17 08:56

    You can now do something like this! Check out "Property Wrappers" - 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"
    
    0 讨论(0)
  • 2020-12-17 08:58

    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. 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)

    FWIW, there's really not a way to do this in Objective-C either.

    0 讨论(0)
提交回复
热议问题