How to Use Fix‐It to Correct Swift Code

By Jesse Feiler

Fix‐It is related to code completion in Swift in that it relies on the background ­processing of the text that you type, but it goes beyond just correcting typos. (Fix‐It is the user interface name for code completion.)

The following figure uses the Master‐Detail Application template to demonstrate this.

image0.jpg

Code completion can help you complete code when you type var myVar: S. However, after you’ve typed (and completed) var myVar: String, you still have a syntax error.

An error message appears on the class declaration. The text is shown at the right (“Class ‘AppDelegate’ has no initializers”), and the red circle in the gutter indicates an error.

This red circle — really a red doughnut — won’t always accompany your error. Some error messages display a small red stop sign in the gutter instead. The red doughnut indicates that Fix‐It is available. Click the doughnut to add a suggested Fix‐It. Press Return, and Xcode implements the Fix‐It.

In this case, the error is the missing initializer for the class. That’s all well and good, but if you’re a beginning Swift developer, what do you do about it?

The Fix‐It provides the solution. Swift requires that every variable and constant have an initial value. Unlike some other languages (including Objective‐C), you cannot have a declared constant or variable that has no value. It has to have some value.

Thus, to adhere to the Swift rules, you can get rid of the error message about the lack of an initializer by setting myVar to a blank string. It’s only a blank string, true, but it’s something. By using it, you don’t have an uninitialized variable, and your error goes away.

This figure shows the Fix‐It and its solution:

image1.jpg

Fix‐It is very powerful. Consider, for example, that instead of var myVar: String you had entered the following line of code:

var myVar: Double

This new code gives you the same Fix‐It message. However, the Fix‐It solution would be different:

var myVar: Double = 0.0

Fix‐It can not only recognize that myVar is uninitialized, but it can also provide an initialization that is the correct type. It gives you a solution that’s syntactically (and contextually) correct.

Note, however, that even a syntactically and contextually correct solution may not be right. The best initialization value for your needs might actually be “No Data” (for the string) or 163.24 (for the double).

Nevertheless, you are far ahead when you use Fix‐It in a case like this — particularly because the solution of providing an initializer does not require creating a separate initializer function. The error message is correct (and creating an initializer called init could solve the problem), but there is this simpler solution: just set a default value to the variable.