Modal class
class Trip: NSObject {
var tripTitle: String
var tripSummary: String
static var trips = [Trip]()
init(tripTitle: String, tripSummary: String) {
self.tripTitle = tripTitle
self.tripSummary = tripSummary
}
class func addTrip(tripTitle: String, tripSummary: String){
let t = Trip(tripTitle: tripTitle, tripSummary: tripSummary)
trips.append(t)
}
}
In Controller
@IBAction func previewButtomPressed(sender: UIButton) {
let tripTitle = tripTitleTxt.text!
let tripSummary = tripSummaryTxt.text!
Trip.addTrip(tripTitle, tripSummary: tripSummary)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowTripPreviewTableViewController" {
let tripPreviewTableViewController = segue.destinationViewController as! TripPreviewTableViewController
tripPreviewTableViewController.trip = Trip //here I am getting an error
}
}
error
Cannot assign value of type 'Trip.Type' to type 'Trip'
tripPreviewTableViewController
var trip : Trip!
I don't know what is the type of your tripPreviewTableViewController.trip
but it makes more sense for me to do:
tripPreviewTableViewController.trip = Trip.trips
Edit
Two ways to do it:
1) You change the type of tripPreviewTableViewController.trip
to [Trip]?
. When you assign the value you can do tripPreviewTableViewController.trip = Trip.trips
2) You can access Trip
class inside your tripPreviewTableViewController
.
In your case, as trips
is an static variable , you do NOT need to pass anything via segue.
Just ask for Trip.trips
when you needed in your destination view ( TripPreviewTableViewController
)
As others have pointed out, you can't assign a Class type to a variable which represents an instance of that class, since the Class is not an instance.
However, if your class represents a trip, why does this class:
have a static class variable to hold an array of trips?
have a class method that creates a new trip and appends it to the array of trips?
If your class is meant to represent a single trip, it should only encapsulate properties and methods that refer to an instance's trip.
It seems like you're trying to also misuse the class to serve as a "global" model which happens to hold an array of trips. If you want to keep track of a collection of trips, it would make your code easier (for you and others) to understand and maintain, if you stored that array of trips outside the Trip
class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.