gpt4 book ai didi

swift - 在 Swift 中,Objective-C 类的属性是否有可能满足 Swift @obj 协议(protocol)计算属性要求?

转载 作者:可可西里 更新时间:2023-10-31 23:44:33 26 4
gpt4 key购买 nike

例如,我想从现有的 Objective-C 类 MyFoo 中提取 Swift 协议(protocol)。我们称此协议(protocol)为 FooProtocol

情况是这样的:

// In Objective-C
@interface MyFoo
@property(nonatomic, copy) NSString *foo;
@end
@implementation MyFoo
// ... -(instancetype)initWithString: is implemented here
@end

// In Swift
@objc protocol FooProtocol {
var foo: String { get set }
}

extension MyFoo: FooProtocol {
// do nothing here!
}

那么我应该被允许这样做:

let theFoo: FooProtocol = MyFoo(string: "Awesome")
NSLog("\(theFoo.foo)") // Prints awesome.

但我被告知“MyFoo 不符合 FooProtocol 协议(protocol)”。好的。很公平,我想协议(protocol)扩展需要一点插入:

extension MyFoo: FooProtocol {
var foo: String! { get { return foo } set { NSLog("noop") }}
}

但是我从编译器中得到的错误看起来像

Getter for 'foo' with Objective-C selector 'foo' conflicts with previous declaration with the same Objective-C selector

我做错了什么?

最佳答案

接口(interface)有不同的签名,因此编译器不知道该做什么。

试试这个:

// In Objective-C
@interface MyFoo
@property(nonatomic, copy) NSString *foo;
@end
@implementation MyFoo
// ... -(instancetype)initWithString: is implemented here
@end

// In Swift
@objc protocol FooProtocol {
var foo: NSString { get set }
}

extension MyFoo: FooProtocol {
// do nothing here!
}

关于swift - 在 Swift 中,Objective-C 类的属性是否有可能满足 Swift @obj 协议(protocol)计算属性要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com