0

So I have the class Caddy:

class Caddy{

        var caddyName: String
        var phoneNumber: Int
        var email: String
        var password: String
        var caddyRank: String
        var caddyLocation: Int
        var proPic: UIImage  
}

I have a array of these custom objects, caddyList.

I need to reference a specific object in the array using a string caddyName.

I then need to change a value of that specific object, specifically the caddyLocation value.

How can I accomplish this using Swift 2.0?

user127182
  • 39
  • 1
  • 3

1 Answers1

0

If order is not important to you, you should use a Dictionary of Caddys instead of an array of Caddys. That would allow O(1) access to any category in the collection. It also is easy to access and modify an object with swift.

// Assume you have two Caddy objects, caddy1 and caddy2
// Create the dictionary
caddies = [caddy1.caddyName: caddy1, caddy2.caddyName: caddy2]  // eg, etc...

// Access and change the caddies location (if the name has a match)
caddies["Bob"]?.caddyLocation = 2

If you want to know when the caddy actually exists and a modification was made, then wrap it in an if let.

let bobCaddyName = "Bob"
if let _ = caddies[bobCaddyName] {
  caddies[bobCaddyName]?.caddyLocation = 2
}
timgcarlson
  • 3,017
  • 25
  • 52