Search code examples
swiftreturndependent-type

Can Swift structs self-delete?


Consider the following:

struct MiniString {
    private(set) var value: String

    init(_ value: String) {
        if value.count < 17 {
            self.value = value
        } else {
            selfDeleteSomehow()
        }
    }
}

Elsewhere this could be instantiated thus:

var ms: MiniString? = MiniString("This string is too long to be accepted")
print(ms) // prints 'nil'

Context: my specific use-case is for a func declaration in a protocol that would return a Double between 0.0 and 1.0, but no higher or lower, something like:

protocol DoubleBetweenZeroAndOneProtocol {
    func getResult() -> DoubleBetweenZeroAndOne
}

Solution

  • You could use a failable initializer:

    struct MiniString {
    
        var value: String { return value_ }
    
        private let value_: String
    
        init?(_ seedValue: String) {
            if seedValue.count < 17 {
                value_ = seedValue
            } else {
                return nil
            }
        }
    }