Book Image

Swift Cookbook

By : Cecil Costa, Cecil Costa
Book Image

Swift Cookbook

By: Cecil Costa, Cecil Costa

Overview of this book

Table of Contents (18 chapters)
Swift Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Avoiding copying of structs


There are times when we are working with structs and we don't want to copy it. In this recipe, we will see this example and the solution for it by creating a small app where the user can see the coordinates of two supposed characters, and we can press a button to change their coordinates to a center point between them.

Getting ready

Create a new single view project called Chapter3 Vector2D. For this recipe, we will need only one new file, which we will call it Position.swift.

How to do it...

Let's create the app that prevents copying of structs:

  1. Let's start with the Model part as usual. Click on the Position.swift file. Let's create a struct with the same name, as follows:

    struct Position:Printable {
        private var x:Int,y:Int
        init(){
            (x,y) = (0,0)
        }
        mutating func moveUp(){
            self.y--
        }
        mutating func moveDown(){
            self.y++
        }
        mutating func moveRight(){
            self.x++
        }
        mutating func moveLeft(){
            self.x...