This is one way of doing it. It's only automatically used when you're saving changes, and in that case all it can do is prevent saving and return an error message. You might display that error message to the user. If that fits your needs, then it's a good approach. You can also run it manually. It might be less useful in other situations, for example importing data from a server API. This is the only built-in technique specifically designed for property validation.
There are other ways-- literally any way that works for you to check that the property values fit your requirements. For example, you could write your own failable initializer, and have it return nil
if any of the arguments are no good. Or have it throw
so it can return an Error
explaining why it can't initialize. Custom code like this won't prevent saving changes, but if you use it carefully it'll still make sure values match your requirements.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…