0

I am creating an application to teach myself swift and iOS in general. In this application, I wish to create an array of "Restaurant" objects, and allow users to create a new Restaurant and append it to the array. Although, when I create a new Restaurant instance, I believe it is just copying the array, and therefore not actually appending anything to it. I was wondering if i could create one array in swift that is accessible to all files, without having to create an instance of that array in another file. (Code Sample below)

    /* The following code is in one view controller*/

    // Create an array of restuarant instances to use within the application.

    var restaurants:[Restaurant] = [
    Restaurant(name: "Cafe Deadend", type: "Coffee & Tea Shop", 
         location: "G/F, 72 Po Hing Fong, Sheung Wan, Hong Kong",  
         phoneNumber: "232-923423", image: "cafedeadend.jpg",  
         isVisited: false),

    Restaurant(name: "Homei", type: "Cafe", location: "Shop B, G/F, 22- 
           24A Tai Ping San Street SOHO, Sheung Wan, Hong Kong", 
           phoneNumber: "348-233423", image: "homei.jpg", isVisited:      
           false),
    Restaurant(name: "Teakha", type: "Tea House", location: "Shop B, 18 
           Tai Ping Shan Road SOHO, Sheung Wan, Hong Kong", 
           phoneNumber: "354-243523", image: "teakha.jpg", isVisited: 
           false)
     ]

// Get properties to create a new restaurant object
@IBOutlet weak var restaurantName: UITextField!
@IBOutlet weak var restaurantType: UITextField!
@IBOutlet weak var restaurantLocation: UITextField!
@IBOutlet weak var restaurantPhoneNumber: UITextField!
@IBOutlet weak var restaurantImageName: UITextField!
@IBOutlet weak var restaurantIsVisited: UITextField!


// Function for when Add Restaurant button is clicked.
@IBAction func addRestaurant(sender: UIButton) {
    var isVisited = false
    // Create local vaiables to the properties once a user enters a new restaurant.
    let name = self.restaurantName.text!
    let type = self.restaurantType.text!
    let location = self.restaurantLocation.text!
    let phoneNumber = self.restaurantPhoneNumber.text!
    let image = self.restaurantImageName.text!
    // check to see what the text inside the text field for is visited is, and then set the variable accordingly.
    if self.restaurantIsVisited.text! == "Yes" {
        isVisited = true
    } else {
        isVisited = false
    }

    //here we add the text into a new restaurant object by invoking the function below:
    createNewRestaurantObjectAndAddItToArrayOfObjects(name, type: type,      
             location: location, number: phoneNumber, image: image, 
             isVisited: isVisited)
     }

    /* Function name speaks for itslef :)
       this method may be unnessecary, but i will go back and fix it      
       later
      */

    func createNewRestaurantObjectAndAddItToArrayOfObjects(name: 
    String,  type:     String, location: String, number: String, image: 
    String, isVisited: Bool) {
        let newRestaurant = Restaurant(name: name, type: type,  
            location: location, phoneNumber: number, image: image, 
            isVisited: isVisited)

    // here i append the new restaurant on to the array of rest objects.
    restaurants.append(newRestaurant)
    print(restaurants.count)
    print(restaurants[21])
    }


    // The code from here on is how i access the array from another swift file, 
    var restaurants = AddRestaurantViewController().restaurants

I hope this code sample helps explain my problem. Thanks!

4
  • What is your actual goal when you say create one array that is accessible to all files? Do you want to store this set of restaurants long term? Do you want to just pass this list to another view controller? If you want to store it, you can look at sharedpeferences, or even create an sqlite database. Commented Apr 20, 2016 at 2:03
  • @nPn I don't think a database is necessary, this application is just to help me learn swift. Yes, I just need to pass it to another view controller Commented Apr 20, 2016 at 2:17
  • The general pattern for that would be, you have some action that would invoke a segue. When that happens you will get a call to prepareForSegue, which will include a segue object, that you can use to get a reference to the "desitination" viewcontoller. You can then pass your array to that next controller by setting a property. BTW, a great way to learn swift/ios is via the itunes university version of cs193p. Commented Apr 20, 2016 at 2:33
  • Thanks! I've tried cs193p, but some of the programming is a little over my head. Commented Apr 20, 2016 at 2:36

3 Answers 3

1

Create class variable that you can access it using class name.

Please find the below code

static var restaurants:[Restaurant] = [
    Restaurant(name: "Cafe Deadend", type: "Coffee & Tea Shop",
        location: "G/F, 72 Po Hing Fong, Sheung Wan, Hong Kong",
        phoneNumber: "232-923423", image: "cafedeadend.jpg",
        isVisited: false),

    Restaurant(name: "Homei", type: "Cafe", location: "Shop B, G/F, 22-24A Tai Ping San Street SOHO, Sheung Wan, Hong Kong",
        phoneNumber: "348-233423", image: "homei.jpg", isVisited:
        false),
    Restaurant(name: "Teakha", type: "Tea House", location: "Shop B, 18 Tai Ping Shan Road SOHO, Sheung Wan, Hong Kong",
        phoneNumber: "354-243523", image: "teakha.jpg", isVisited:
        false)
]

To use this variable you have to use class instead of instance, as below

AddRestaurantViewController.restaurants.append(newRestaurant)
    print(AddRestaurantViewController.restaurants.count)
    print(AddRestaurantViewController.restaurants[21])

And you can use this variable from out side of the class as below

var restaurants = AddRestaurantViewController().restaurants
Sign up to request clarification or add additional context in comments.

Comments

0

Based on your comment about wanting to share your array with say another view controller, the basic idea is that. some action would happen in your current view controller and you might want to move to a different view controller, but pass some info along to that controller (like your array).

The way that would happen is the view controller you want to start up and pass data to would have a property that can accept the data you want to share, for example an a suppliedRestaurants property similar to what you have in the current controller. Then when the segue is invoked a method prepareForSegue on your current controller will be called in which you will get a chance to set the property in the destination controller. This would just be setting the reference in the destination to the reference in the current controller.

Here is a quick example. // MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "EditFromMyCircle" {
    if let destinationViewController = segue.destinationViewController.contentViewController as? UserPermissionsTableViewController {
      if let sender = sender as? OurLatitudeMyCircleTableViewCell {
        destinationViewController.otherUserId = sender.userId
      }
    }
  }
}

In this example someone clicked on a user entry in a table of mine, and I am going to pass the user id to my controller that will also the user to edit some permissions. In this case I am just passing a user id to the next controller, but it could be anything.

This is a very common pattern in iOS.

2 Comments

Eep the if let pyramid of doom!
ha, just noticed this comment ... yes this was probably swift 1.0 ... later versions do help "flatten" the if let pyramid of doom
0

This is a "flatter" version of @nPn's answer

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "EditFromMyCircle" {
    guard let destinationViewController = segue.destinationViewController.contentViewController as? UserPermissionsTableViewController else { return }
    guard let sender = sender as? OurLatitudeMyCircleTableViewCell else { return }
    destinationViewController.otherUserId = sender.userId
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.