I am using Xcode 8.3 and Swift 3.0. This is my first attempt at using Swift after going through the Jump Right In tutorial provided by Apple.
I have a data model file that defines a class:
class Location: NSObject, NSCoding {
//MARK: Properties
var name: String
var number: Int
var item: String
var visited: Bool
var coords: [Coordinates]
//MARK: Types
struct Coordinates {
// default values are for a location
let latitude: Double = 35.0
let longitude: Double = -120.0
}
//MARK: Initialization
init(name: String, number: Int, item: String, visited: Bool, coords: [Coordinates]) {
// Initialize stored properties
self.name = name
self.number = number
self.item = item
self.visited = visited
self.coords = coords
}
}
I also have a ViewController that I want to use the data in. Right now, I'm still writing/learning, so I'm having it load a sample piece of data that I enter by hand:
class ViewController: UIViewController {
//MARK: Properties
// an array of the locations
var locations = [Location]()
override func viewDidLoad() {
super.viewDidLoad()
// Load a sample location.
locations[0] = Location(name: "foo", number: 1, item: "bar", visited: false, coords: [Location.Coordinates(latitude: 36.0, longitude: -121.0)])
os_log("Locations successfully loaded on map screen.", log: OSLog.default, type: .debug)
}
}
The problem part is clearly coords: [Location.Coordinates(latitude: 36.0, longitude: -121.0)]
, which I added after the code was otherwise functioning. The error Xcode gives me is:
Cannot invoke value of type 'Location.Coordinates.Type' with argument list '(latitude: Double, longitude: Double)'
When I search for this error, I find this question, which looks very similar to me. So, I do as the accepted answer says:
I create an instance of the Coordinates type in the Location class (adding
var instanceOfCoordinates = Coordinates()
after the definition of Coordinates)I also create an instance of the Location class in the ViewController class (adding
let instanceOfLocation = Location.self
after declaring the locations property)I update the problematic bit of code to
coords: [instanceOfLocation.instanceOfCoordinates(latitude: 36.0, longitude: -121.0)]
I get a different error:
Instance member 'instanceOfCoordinates' cannot be used on type 'Location'
EDIT: Adding [] around the part of the code after coords:
but before the last )
doesn't change the errors.
What I want is be able to keep the coordinates as a structure within the location so that they are always together and I can use dot referencing to get the values in the form locations[0].coords[index].latitiude
and locations[25].coords[index].longitude
and so on. Eventually this will be used to populate a google map with pins.
I am sure there are a great many subtleties (and not so subtle) of Swift lost on me, but usually searching and tinkering works out, but not this time.
Can someone please demonstrate what I'm doing wrong here?