在目标C中不可见的swift init [英] swift init not visible in objective-C
问题描述
我试图在Swift
中创建init
函数,并从Objective-C
创建实例.问题是我在Project-Swift.h
文件中看不到它,并且在初始化时找不到该函数.我有一个定义如下的函数:
I'm trying to create init
functions in Swift
and create instances from Objective-C
. The problem is that I don't see it in Project-Swift.h
file and I'm not able to find the function while initializing. I have a function defined as below:
public init(userId: Int!) {
self.init(style: UITableViewStyle.Plain)
self.userId = userId
}
我什至尝试放置@objc(initWithUserId:)
,并且再次出现相同的错误.还有什么我想念的吗?如何使Objective-C
代码可见构造函数?
I even tried putting @objc(initWithUserId:)
and I keep getting the same error again. Is there anything else I'm missing? How do I get the constructor visible to Objective-C
code?
我为此阅读了以下内容:
I read the below for this:
推荐答案
您看到的问题是Swift无法桥接可选值类型-Int
是值类型,因此Int!
不能被桥接.可选引用类型(即任何类)可以正确桥接,因为它们在Objective-C中始终可以是nil
.您的两个选择是使参数成为非可选参数,在这种情况下,它将作为int
或NSInteger
桥接到ObjC:
The issue you're seeing is that Swift can't bridge optional value types -- Int
is a value type, so Int!
can't be bridged. Optional reference types (i.e., any class) bridge correctly, since they can always be nil
in Objective-C. Your two options are to make the parameter non-optional, in which case it would be bridged to ObjC as an int
or NSInteger
:
// Swift
public init(userId: Int) {
self.init(style: UITableViewStyle.Plain)
self.userId = userId
}
// ObjC
MyClass *instance = [[MyClass alloc] initWithUserId: 10];
或使用可选的NSNumber?
,因为可以将其桥接为可选值:
Or use an optional NSNumber?
, since that can be bridged as an optional value:
// Swift
public init(userId: NSNumber?) {
self.init(style: UITableViewStyle.Plain)
self.userId = userId?.integerValue
}
// ObjC
MyClass *instance = [[MyClass alloc] initWithUserId: @10]; // note the @-literal
但是,请注意,您实际上并没有像对待可选参数那样对待参数-除非self.userId
也是可选参数,否则您将自己设置为可能会导致运行时崩溃.
Note, however, you're not actually treating the parameter like an optional - unless self.userId
is also an optional you're setting yourself up for potential runtime crashes this way.
这篇关于在目标C中不可见的swift init的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!