Swift For Dummies
Book image
Explore Book Buy On Amazon

Constants and variables have to be initialized before use in Swift. However, there’s more than one way to do this and get on with your code. If you’re not sure whether your approach will work, test out your initialization strategies in a playground. Here’s how:

  1. Create a new playground with a single declaration, like this one:

    var x
  2. Try using your variable, x, in some way, like this:

    x = x + 2

    In this case, you’ll get an error.

  3. To address the error, add an initializer to your declaration, like this:

    var x = 2

    This takes care of the problem.

Inside a class or structure, you use an init for each stored property. Here’s an example:

struct myStruct {
 var myStructVal: Double
 init (fromConstant my100: Double) {
  self.myStructVal = 100
 }
 init (fromParam myVal: Double) {
  self.myStructVal = myVal
 }
 init () {
  self.myStructVal = 1000;
 }
}

Here are the strategies:

  • Initialize from a default value. Example:

    init () {
     self.myStructVal = 1000;
    }
  • Initialize with a constant ignoring any values passed in. This might be useful in testing. Example:

    init (fromConstant my100: Double) {
     self.myStructVal = 100
    }
  • Initialize with a parameter. You can use its value of perform a calculation with the parameter’s value. Example:

init (fromParam myVal: Double) {
 self.myStructVal = myVal
}

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

This article can be found in the category: