-4

I have optional String. What is want is, when trying to access it variable throw an error if it nil or empty. I want something like:

var myString: String? {
    get {
    guard !self.isEmpty || self == nil else { // throw error }
    return self
    }
}

Is it possible to write such in Swift? Thanks.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

2 Answers2

1

First notice that myString cannot be nil as it is not an optional. If you want to allow storing nil declare it as an optional:

var myString: String?

checking for self == nil is redundant since if self is nil this property can never be accessed AND you cannot throw an exception from a computed property so throwing won't work either.

You can declare it as private and provide a getter method that can check if its nil or empty and throw accordingly }

If you do not want myString to ever be nil then do not declare it as optional. If you do not want the string to be empty than avoid that when setting the string.

private(set) myString: String // You cannot set the string directly outside of the class but you can access it freely

func setMyString(withValue value: String)
{
    if (value.isEmpty)
    {
        throw ... // 
    }

    myString = value
}

regarding throwing errors check this link

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • ok, how to do that - You can declare it as private and provide a getter method that can check if its nil or empty and throw accordingly } ? Can you provide compiling code snippet? – Evgeniy Kleban Feb 28 '18 at 12:28
  • is it neccessary to make it private(set) ? – Evgeniy Kleban Feb 28 '18 at 12:49
  • not necessary but then the string can be manipulated from outside the class and then any value (including empty string) can be stored in it – giorashc Feb 28 '18 at 13:14
1

In swift, a computed property cannot throw an exception - if you want to be sure, check out Throwing Functions and Methods section of Swift 4.1 language reference. So even if the rest of your code made sense, you simply cannot throw an exception from a computed property.

Anyway, test self == nil makes no sense - self cannot really ever be nil. If an object is nil, it does not exist, thus you cannot access any of its properties/methods (it does not exist, what would you be accessing?).

E.g., if you try to call yourObject?.myString, the getter for myString will NOT be executed at all, because yourObject is nil, it does not exist. If you try to force it using ! it will crash right away.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90