swift - 访问父属性

标签 swift

我想访问我编写的父注释类的属性来检查它的值。

Annotation.swift

enum AnnotationType: Int {
    case AnnotationDefault = 0
    case AnnotationAED
    case AnnotationResponder
    case AnnotationIncident
}

class Annotation: NSObject, MKAnnotation {

    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subTitle: String
    var type: AnnotationType

    init(coordinate: CLLocationCoordinate2D, title: String, subTitle: String, type: AnnotationType) {
        self.coordinate = coordinate
        self.title = title
        self.subTitle = subTitle
        self.type = type
    }

    func getType() -> AnnotationType {
        return self.type
    }
}

AEDAnnotation.swift

class AEDAnnotation : Annotation {
    let aed: AED

    init(aed: AED) {
        self.aed = aed
        super.init(coordinate: aed.coordinate, title: aed.street, subTitle: aed.owner, type: aed.annotationType)
    }

    func getAnnotationType() -> AnnotationType {
        return super.getType()
    }
}

我创建一个这样的注释:

let annotation = AEDAnnotation.init(aed: aed)
self.annotationArray.append(annotation)

如果我循环遍历数组,我会看到其中有有效的 AEDAnnotations。但为什么我无法访问我所要求的 Annotation.swift 的底层属性。

for item in self.annotationArray {
    print(item.getType)
}

这不起作用。但是我如何才能访问 Annotation.swift

的属性 type

我收到的错误消息是: “MKAnnotation”类型的值没有成员“getType”

最佳答案

该错误表明 item 的类型为 MKAnnnotation。如果您想将其视为不同类型,则需要对其进行强制转换。请尝试以下操作:

for item in self.annotationArray {
    if let myAnnotation = item as Annotation {
        print("\(myAnnotation.getType().rawValue)")
    }
    else {
        print("Annotation was not an Annotation type")
    }
}

关于swift - 访问父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245025/

相关文章:

swift - ARAnchor到底是什么?

Swift 枚举, `OR` 均衡

swift - Xcode 7.3 已弃用 "++"和 "--"运算符

regex - 如何在 swift 项目中查找非本地化字符串

swift OSX : simultaneous command + non modifier key events

ios - 是否有原生图像附加到 ios Storyboard上的按钮?

IOS + Swift,如何重定向到 iTunes 购买页面

ios - 自定义 TableViewCell Swift

ios - UICollectionView 中的多种单元格类型

swift - 识别范围重叠