gpt4 book ai didi

objective-c - 使用 Objective-C 结构时防止 takeRetainedValue 或 takeUnretainedValue

转载 作者:行者123 更新时间:2023-11-30 13:17:55 28 4
gpt4 key购买 nike

我正在使用this approach将我的字符串常量保持在一起。使用该帖子中的相同示例:

MONExtResult.h

struct MONExtResultStruct {
__unsafe_unretained NSString * const AppID;
__unsafe_unretained NSString * const ErrorCode;
__unsafe_unretained NSString * const Progress;
};

extern const struct MONExtResultStruct MONExtResult;

MONExtResult.m

const struct MONExtResultStruct MONExtResult = {
.AppID = @"appid",
.ErrorCode = @"errorcode",
.Progress = @"progress"
};

这可以在 Objective-C 中使用,如下所示:

NSString *str = MONExtResult.AppID;

但是,当我尝试在 Swift 中使用它时:

let appID: String = MONExtResult.AppID

...我收到错误:

Cannot convert value of type 'Unmanaged<NSString>!' to expected argument type 'String'

这是因为我需要从 unmanaged wrapper 中获取值然后将其转换为字符串:

let appID: String = MONExtResult.AppID.takeUnretainedValue() as String

是否有任何方法可以注释 Objective-C 代码,以防止需要像使用 CF_IMPLICIT_BRIDGING_ENABLEDCF_RETURNS_RETAINED 那样调用 takeUnretainedValue C 函数?

更新:这些常量必须可由 Objective-C 和 Swift 访问。否则我只会使用带有 String 原始值的 Swift 枚举。

最佳答案

我能够构建的最接近的是:

enum MONExtResult: String {
case AppID = "com.me.myapp"
case ErrorCode = "game over"
case Progress = "vote Tuesday"
}

extension String {
init(const: MONExtResult) {
self = const.rawValue
}
}

let err = String(MONExtResult.ErrorCode)

值得注意的是,这不起作用:

let appID: String = MONExtResult.AppID

由于末尾缺少 .rawValue,但只要您愿意接受大致相同数量的字符和略有不同的语法,我相信这会达到您的预期。

关于objective-c - 使用 Objective-C 结构时防止 takeRetainedValue 或 takeUnretainedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040097/

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