MKMapView: How do I set mapType? (beginner question)

Hi

I am an absolute beginner in Swift.

A friend helped me setup a test app that displays a map using Map Kit. This is the part that creates the actually map:

Code Block
class KMLViewerViewController: UIViewController, MKMapViewDelegate {
let map = MKMapView()
// etc. ...
}


I tried to set mapType to hybridFlyover in different ways, like this for instance:
Code Block
let map = MKMapView(.mapType = .hybridFlyover )

But everything returns an error...
Can any one help me, please?
Where can I find an explanation of swift syntax?

Answered by Claude31 in 674250022
There is no conenience init for MKMapView that let you declare the mapType as an init parameter.

You should thus write:

Code Block
import MapKit
class KMLViewerViewController: UIViewController, MKMapViewDelegate {
let map = MKMapView()
// etc. ...
override func viewDidLoad() {
super.viewDidLoad()
map.mapType = .hybridFlyover
}
}

Note that
map.mapType = .hybridFlyover
must be inside a func ; it cannot be at the class level just after etc…

Unless you declare it as a computed var:
Code Block
var map : MKMapView {
let aMap = MKMapView()
aMap.mapType = .hybridFlyover
return aMap
}


Accepted Answer
There is no conenience init for MKMapView that let you declare the mapType as an init parameter.

You should thus write:

Code Block
import MapKit
class KMLViewerViewController: UIViewController, MKMapViewDelegate {
let map = MKMapView()
// etc. ...
override func viewDidLoad() {
super.viewDidLoad()
map.mapType = .hybridFlyover
}
}

Note that
map.mapType = .hybridFlyover
must be inside a func ; it cannot be at the class level just after etc…

Unless you declare it as a computed var:
Code Block
var map : MKMapView {
let aMap = MKMapView()
aMap.mapType = .hybridFlyover
return aMap
}


But everything returns an error...
Can any one help me, please? 
Where can I find an explanation of swift syntax?

A few more comments:
  • when you have error, please post the error

  • what you tried:

Code Block
let map = MKMapView(.mapType = .hybridFlyover )
is a wrong syntax, as you have noticed.

When you call a class initialiser that has parameters, it would be something like this syntax:
Code Block
let map = MKMapView(mapType: .hybridFlyover)

No dot before the label for the parameter
no equal but colon sign
But this does not work here because no such initialiser exist (you could subclass MKMapView and create such a convenience init)

This works:
Code Block
import MapKit
class MyOwnMKMapView : MKMapView {
convenience init(mapType: MKMapType) {
self.init()
self.mapType = mapType
}
}
class KMLViewerViewController: UIViewController, MKMapViewDelegate {
let map = MyOwnMKMapView(mapType : .hybridFlyover ) // You use your subclass
// etc. ...
}


Thank you very much for your 2 answers!
MKMapView: How do I set mapType? (beginner question)
 
 
Q