11

我在 swift 中遵循了 Ray Wenderlich MapKit 教程:http ://www.raywenderlich.com/90971/introduction-mapkit-swift-tutorial当我创建 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()
}
}

请帮忙!

4

4 回答 4

20

分析器在文档中:我们在MKAnnotation 协议参考页面上看到该属性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()
    }

}

专业提示:在 Xcode 中,在您的对象或定义(MKAnnotation在您的情况下)上 CMD+CLICK 以查看协议是如何声明的以及它的要求是什么。

于 2015-11-04T14:48:02.390 回答
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?问题就会消失。

于 2015-11-04T14:48:04.360 回答
1

相应地改变它:

var title: String?

var subtitle: String?
于 2017-03-08T09:05:32.450 回答
0

除以上内容外,截至 2016 年 swift 3

如果您遵循上述教程,则需要解决: var subtitle: String{ return locationName }

to : public var subtitle: String?{ return locationName }

希望这也能澄清一些事情

于 2017-02-02T16:43:01.160 回答