繁体   English   中英

将可选的 @objc 枚举类型传递给 @objc 协议

[英]Passing optional @objc enum type into @objc protocol

我正在尝试在@objc 协议中创建一个可选的 function,documentType 也是@objc 枚举。 但我收到了这个错误:

方法不能标记@objc,因为Objective-C中不能表示参数的类型

我的源代码:

@objc enum DocumentType: Int {
    case pdf
    case png
}

@objc protocol ImageDocumentEditorProtocol: class {
    @objc optional func imageDocumentEditorDidCancel(documentType: DocumentType?)
}

我该如何解决这个问题? 谢谢

问题是? .

在 Objective-C 中,您不能表示原始类型的 Optional。

使它成为非可选的,或者找到另一种方式。

只需删除 DocumentType 上的可选项,因此 function 将是:

@objc optional func imageDocumentEditorDidCancel(documentType: DocumentType)

如果你想在这里有代表 nil 值的东西,你可以在枚举中为它添加另一个案例,如下所示:

@objc enum DocumentType: Int {
    case pdf
    case png
    case none
}

Objective-C 没有可选的枚举。 枚举必须是非可选的。 类可以是可选的,而不是枚举:(

一种解决方法是添加一个案例:

@objc enum DocumentType: Int {
    case pdf
    case png
    case none
}

并改用非可选类型DocumentType

当然,这使得非可选DocumentType s 不可表示。 要同时表示可选和非可选DocumentType ,您需要两种类型:

@objc enum DocumentType: Int {
    case pdf
    case png
    
    func asOptionalDocumentType() -> OptionalDocumentType {
        switch self {
        case .pdf: return .pdf
        case .png: return .png
        }
    }
}

extension Optional where Wrapped == DocumentType {
    func asOptionalDocumentType() -> OptionalDocumentType {
        self?.asOptionalDocumentType() ?? .none
    }
}

@objc enum OptionalDocumentType: Int, ExpressibleByNilLiteral {
    
    case pdf
    case png
    case none
    
    func asDocumentType() -> DocumentType? {
        switch self {
        case .pdf: return .pdf
        case .png: return .png
        case .none: return nil
        }
    }
    
    init(nilLiteral: ()) {
        self = .none
    }
}

我添加了转换方法,以便在它们之间轻松转换,但它们在技术上不是必需的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM