我有一个用 Objective C 编写的库函数,它带有一个指向 NSMutableArray 的指针。但是,当我尝试使用 Swift 数组调用它时出现此错误:
DiscoverViewController.swift:34:20: Could not find an overload for 'init' that
accepts the supplied arguments
但是,如果我传递 nil
,它就会起作用。这是有道理的。
这是一个 Objective-C 的例子:
int ex:(NSMutableArray *)in { return in.count; }
还有一个 Swift 的例子:
ex([1,2,3,4]) // doesn't compile
ex(nil) // does compile
我需要做什么才能将 Swift 数组转换/强制转换为我的库函数正在寻找的 NSMutableArray 类型?
如果我的示例过于简单,这里是完整的方法签名:
- (id) initWithTitle: (NSString *) title place: (PublicPlaceInfo *) place
datetimeInterval: (DateTimeInterval *) datetimeInterval costBracket: (int)
costBracket creatorId: (PersonID) creatorId cover: (Url) cover experienceId:
(ExperienceID) experienceId numJoined: (int32_t) numJoined relatedJoined:
(NSMutableArray *) relatedJoined;
然后我知道它在 relatedJoined 部分失败了,因为我将所有其他可能匿名的实例化转换为变量。我不得不说,这肯定不是最有帮助的编译错误..
最佳答案
ex([1,2,3,4]) // doesn't compile
这是因为您传递给它的是普通数组,而不是可变数组。首先尝试将其转换为可变数组:ex(NSMutableArray([1,2,3,4]))
ex(nil) // does compile
nil
是 NSMutableArray?
的有效参数,这就是它起作用的原因。
关于ios - 在 Swift 中为 Objective C 函数提供 NSMutableArray 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022573/