试图在Swift中实现ObjectiveC协议

时间:2015-03-04 21:29:05

标签: objective-c swift inheritance

我试图在Swift中实现以下协议,它是用objective-c编写的,但我仍然收到编译器错误,说该类不符合协议。我究竟做错了什么?我已经尝试设置getter和setter并应用@NSCopying标志,但无济于事。

#import <Foundation/Foundation.h>

@protocol AIConfiguration <NSObject>

@property(nonatomic, copy) NSURL *baseURL;

@property(nonatomic, copy) NSString *clientAccessToken;

@property(nonatomic, copy) NSString *subscriptionKey;

@end

这是我的实施

class AIMyConfiguration : NSObject, AIConfiguration {

    var baseURL : NSURL
    var clientAccessToken : NSString
    var subscriptionKey : NSString

    override init() {
        super.init()
    }
}

谢谢

1 个答案:

答案 0 :(得分:1)

此Objective-C协议:

@protocol AIConfiguration <NSObject>
@property(nonatomic, copy) NSURL *baseURL;
@property(nonatomic, copy) NSString *clientAccessToken;
@property(nonatomic, copy) NSString *subscriptionKey;
@end

被翻译成Swift:

protocol AIConfiguration : NSObjectProtocol {
    @NSCopying var baseURL: NSURL! { get set }
    var clientAccessToken: String! { get set }
    var subscriptionKey: String! { get set }
}

所以你必须实现像:

ImplicitlyUnwrappedOptional

class AIMyConfiguration: NSObject, AIConfiguration {
    @NSCopying var baseURL: NSURL!
    var clientAccessToken: String!
    var subscriptionKey: String!

    override init() {
        super.init()
    }
}

Optional

class AIMyConfiguration: NSObject, AIConfiguration {
    @NSCopying var baseURL: NSURL?
    var clientAccessToken: String?
    var subscriptionKey: String?

    override init() {
        super.init()
    }
}

OR非可选:

class AIMyConfiguration: NSObject, AIConfiguration {
    @NSCopying var baseURL: NSURL
    var clientAccessToken: String
    var subscriptionKey: String

    init(baseURL:NSURL, clientAccessToken:String, subscriptionKey:String) {
        self.baseURL = baseURL
        self.clientAccessToken = clientAccessToken
        self.subscriptionKey = subscriptionKey
        super.init()
    }
}