Declaring and using custom attributes in Swift

前端 未结 2 1913
花落未央
花落未央 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"
    

提交回复
热议问题