Programming in Swift - Part 40: Part 5: Structures: | Ray Wenderlich

Learn how to group data and functionality together in Swift, using a value type called structures.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3535-programming-in-swift/lessons/40

Hi,

When I first downloaded structure-final.playground, it looks like the code works perfectly but there is "Use of unresolved identifier ā€˜distanceā€™ on line 13. I guessed the cause of the problem and changed some codes but couldnā€™t solve the issue.

Please help me understand why this error appears.

Ah - sorry about that. I just checked and the problem is the distance() function needs to be placed before the struct DeliveryArea.

This is because Swift playground executes everything in the playground in order, and if you donā€™t declare the distance() function before you try and use it inside DeliveryArea, the playground doesnā€™t know the distance() function exists.

I hope that helps, and let me know if you have any other questions! :]

Thanks for your quick reply. I copied all the codes except ā€˜import Foundationā€™ to inside viewDidLoad() in viewController.swift under newly created swift project. Then Xcode says ā€œStruct declaration cannot close over value 'distance defined in outer scopeā€ on the same line.

I still donā€™t figure out whether it is a matter of playgroundā€™s execution order.
Need help.

Remember that Playgrounds and Xcode projects work in slightly different ways.

  • In Playgrounds, you put all of your code into a single file, that shares the same global scope.
  • In Xcode projects, you tend to have separate Swift files for each structure or class, or global functions/variables.

Hereā€™s an example of the code from the playground moved over to an Xcode project:

Struct.zip (27.7 KB)

  • Location.swift: Stores the Location structure.
  • DeliveryArea.swift: Stores the DeliveryArea structure.
  • Globals.swift: Stores the three global variables and two global functions. Note in real apps itā€™s best practice to avoid global functions/variables as much as possible, but itā€™s OK for learning purposes.
  • ViewController.swift: I put the rest of the code in viewDidLoad().

I hope that helps!

Thank you so much. I learned a lot from your zipped code.

I have a question. If a structure is not mutably, then what is the point to use ā€œvarā€ in a structure?

This topic was automatically closed after 166 days. New replies are no longer allowed.