Uploaded image for project: 'Swift'
  1. Swift
  2. SR-10950

Property wrappers: @autoclosure not working?

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Environment:

      Description

      Maybe I'm misunderstanding something, but does adding @autoclosure to the init(initialValue: ) initializer of a property wrapper actually have any effect?

      I copied the sample code for Lazy from the SE-0258 proppoal, and then I initialize the lazy value with a closure that prints when it's getting called.

      Paste this code into a file "propertywrapper.swift":

      // ===================================
      // Lazy type from SE-0258
      // ===================================
      @propertyWrapper
      public enum Lazy<Value> {
        case uninitialized(() -> Value)
        case initialized(Value)
        
        /// Creates the lazy value without initializing it.
        /// - Parameter initialValue: The initializer function that's used to initialize the value on first access.
        public init(initialValue: @autoclosure @escaping () -> Value) {
          self = .uninitialized(initialValue)
        }
        
        public var value: Value {
          mutating get {
            switch self {
            case .uninitialized(let initializer):
              let value = initializer()
              self = .initialized(value)
              return value
            case .initialized(let value):
              return value
            }
          }
          set {
            self = .initialized(newValue)
          }
        }
      }
      
      
      // ===================================
      // Usage
      // ===================================
      
      struct N {
          @Lazy var number: Int
      }
      
      print("++ Initializing N")
      var n = N(number: { () -> Int in
          print("-- Initializing Lazy storage")
          return 23
      }())
      print("++ Printing number")
      print(n.number)
      

      Actual output (Swift 5.1 dev snapshot 2019-06-16a):

      ++ Initializing N
      -- Initializing Lazy storage
      ++ Printing number
      23
      

      Note that "-- Initializing Lazy storage" appears before "++ Printing number". I would have expected these lines to be reversed because of the @autoclosure attribute of the init(initialValue: ) initializer.

      Expected output:

      ++ Initializing N
      ++ Printing number
      -- Initializing Lazy storage
      23
      

        Attachments

          Activity

            People

            • Assignee:
              roop Roopesh Chander S
              Reporter:
              ole Ole Begemann
            • Votes:
              0 Vote for this issue
              Watchers:
              7 Start watching this issue

              Dates

              • Created:
                Updated: