我在swift:http://www.raywenderlich.com/90971/introduction-mapkit-swift-tutorial中遵循了Ray Wenderlich MapKit教程,当我创建Artwork类时,我得到了标题中写的错误。我不知道自己该做什么。 这是代码:
class Artwork: NSObject, MKAnnotation {
let title: String
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate
super.init()
}
}
请帮忙!
答案 0 :(得分:19)
anser在文档中:我们在MKAnnotation protocol reference页面上看到属性title
必须是可选项。
这正是错误消息告诉您的:title
的可选性不正确。
相应更改:
class Artwork: NSObject, MKAnnotation {
var title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate
super.init()
}
}
ProTip:在Xcode中,CMD +点击您的对象或定义(在您的案例中为MKAnnotation
),以了解协议的声明方式及其要求。
答案 1 :(得分:3)
MKAnnotation协议要求title为可选类型:
public protocol MKAnnotation : NSObjectProtocol {
// Center latitude and longitude of the annotation view.
// The implementation of this property must be KVO compliant.
public var coordinate: CLLocationCoordinate2D { get }
// Title and subtitle for use by selection UI.
optional public var title: String? { get }
optional public var subtitle: String? { get }
}
只需将标题变量声明为:let title: String?
,问题就会消失。
答案 2 :(得分:1)
相应更改:
var title: String?
var subtitle: String?
答案 3 :(得分:0)
除上述内容外 截至2016年swift 3
如果你按照上面的教程,你将需要解决: var subtitle:String { return locationName}
到: public var subtitle:String?{ return locationName}
希望过于澄清一些事情