[Pitch] nonoptional set

At times it makes sense to have a computed property return optional values whilst only accepting non-optional values. For example, for a Validation property wrapper:

// vastly simplified example
@propertyWrapper
struct Validation {
    private var input: String = ""
    var wrappedValue: String? {
        get {
            if !input.isEmpty {
                return input
            } else {
                return nil
            }
        }
        nonoptional set {
            input = newValue
        }
    }
}

@Validation var name = ""
print(name) // nil, because an empty string is invalid input
name = "David"
print(name) // "David", because it's a valid input
name = nil // 🛑 error: property cannot be explicitly set to nil

This would also help with certain things like enum extraction/embedding which follows this same prism optic, although that's been extensively discussed in a dedicated thread so I won't give any specific examples here.

2 Likes

Here's the most recent previous thread on this, though coming at it from the other direction. :-)

2 Likes

Oh I totally missed this! I actually hearted it back in the day but forgot about it. Any mods reading please feel free to lock this thread to direct people to that one instead.

2 Likes