How are options declared in Swift
Many programming languages differentiate between value and reference types. Value types are intended for elementary data, especially numbers. Reference types, on the other hand, contain references to objects. They can be empty, i.e. not initialized.
Swift also differentiates between value and reference types. However, in Swift a lot is a value type that would be a reference type in other languages - arrays, dictionaries, sets, etc. But the real specialty is the handling of the state, which is called in Swift:
- "Ordinary variables" - regardless of whether they are value or reference types - must be initialized before they are used for the first time; In classes, the initialization must take place within the scope of the declaration or by the init function.
The status is only permitted if the variable is also marked as »Optional«. Optionals are available for both value and reference types.
Declaration of variables
"Ordinary" variables are either initialized immediately - this also results in their type (,). Or they are declared with the specification of a type. Initialization can take place later, but you can got to take place before the first readout; otherwise the compiler returns an error.
Optional are indicated in the declaration by a following question mark or exclamation mark (to). As long as they are not explicitly initialized, you have the value.
Variables versus constants Swift uses the keywords and makes a distinction between variables and constants. The examples presented here use throughout. In principle, however, optionals are also conceivable for constants, although this is less common in practice. In this case there is only one one-time Initialization allowed. The compiler ensures this.
Ordinary Optionals versus Implicitly Unwrapped Optionals
As the previous example showed, there is two Ways to declare optionals: either with an exclamation mark or with a question mark. The difference is expressed in how the variable behaves when accessing the data.
Ordinary optionals must be explicitly converted into the underlying data type with a trailing exclamation mark each time they are read out. The statement is not allowed because the plus operator can add two integers, but not an optional and an integer.
The following exclamation mark forces a conversion of the optional into the underlying data type - i.e. into an integer. If it turns out that this contains optional, an error will occur!
If, on the other hand, optionals are declared in the form, the conversion to the underlying data type, ie the so-called »unwrapping«, takes place automatically. But of course there will be an error here too, should it contain optional.
Implicitly unwrapped optionals are often used for properties that are not initialized immediately in the init function, but rather later. In iOS and OS X programming, you will always come across optionals, especially with outlets. The following variable is only initialized shortly before the view appears. The variable can be used once the method has been called.
The use of Implicitly Unwrapped Optionals saves having to add the exclamation mark in all other methods and thus leads to a somewhat clearer code.
nil test and if-let
Before reading out options, you usually have to check whether or not valid data is available. One possibility is to simply query or.
With you can combine the test with an assignment. If the expression on the right-hand side of the assignment is not the same, then the value of the optional is stored in the variable on the left-hand side. The unpacked optional is saved in, and the data type is:
-Constructions are so common in Swift that there are a number of syntax variations. So you can connect with the casting operator.
Several assignments can be made at once:
Before or you can specify an optional condition. Only when this is fulfilled and the options are not equal, the block is executed:
After the assignments, you can use to formulate another condition that already refers to the new variables:
The keyword can only be used once to all assignments are used. Several conditions can be linked by logical operators such as or:
In practice, the resulting commands rarely look as clear as in the examples above. The endlessly long method and parameter names of the iOS and OS X libraries lead to monster commands that extend over many lines. Two examples from practice:
Occasionally, whole chains of optionals arise: If an option is not equal, then a method should be applied to it. However, the result is itself an optional - and if it is also unequal, then one of its properties should be read out.
The above code can be used in one- Summarize the command:
But there is an even more elegant way. Swift provides the operator combination for such cases: if the previous expression is, then the end result is, otherwise the following method or property is evaluated - and so on. "The Swift Programming Language" is the name of this multi-linked test Optional chaining. The abbreviation for the above code is thus:
Optional chaining is particularly popular in two variants:
- has the effect that the method is only called if the preceding optional expression is not. Otherwise the statement is ignored and no error occurs. So you save yourself cumbersome code of the kind.
has the same effect that the property is only changed if the preceding optional expression is not the same. Again, you save yourself the test.
Curse or blessing?
Dealing with optionals takes getting used to. The many question marks and exclamation marks do not necessarily make the code more readable. -Monster commands do not contribute to the good understandability of the code either.
The reason for the relatively bulky syntax is that it can be used to avoid unwanted access to an uninitialized variable, which is a common problem in other programming languages (null pointer exception).
In itself, the idea is good - if optionals were the exception and non-optional variables were the rule. In practice, however, it is precisely the opposite: when developing iOS or OS X programs, it often appears that almost every property or method provides options. So you have to constantly secure your code against the case that a variable or an expression does deliver.
After a few months you get used to optionals just as you get used to other peculiarities of various programming languages. But there may not be any real enthusiasm for the concept. This is probably less due to the idea itself than to the fact that not even Apple can turn all its frameworks and libraries upside down overnight. The Foundation, Cocoa and Cocoa Touch were developed before Optionals existed - and unfortunately you notice that with every line of code you write.
Incidentally, blogger David Kopec came to almost the same conclusions, from whose post My Experience Building a Small Mac App in Swift I quote a few sentences:
The big problem with optionals though is interacting with the Cocoa frameworks. I feel like Swift was designed for most variables to be non-optional, non-nullable values (I could be wrong of course) and optionals are supposed to be the special cases. But instead, due to having to work with the Objective-C Cocoa frameworks, almost everything is an optional.
- How is life on campus at DCRUST
- Who is the fastest pianist in the world
- Which employees do Launch Academy graduates hire?
- Will we inherit data
- Which is the strongest radioactive element
- How many industries are there in biology
- How is DIRECTV installed in apartments
- How do I remove a pedal crank
- Why do people have to go
- How can I do better at work?
- What is a form that cannot exist
- Uhh is an English word
- How does a fusion ramjet engine work
- Which moon has more water than the earth?
- Where will the value accumulate in 3D printing
- What is Devrani's name in English
- How is the life of Shahrukh Khans
- Can a person track B Ed
- What determines an individual's risk tolerance
- Can an L1 visa holder change jobs?
- What cures RSO
- Goldfish eat pond snails
- What is a deep probability model
- How can I watch viral sex videos