gpt4 book ai didi

objective-c - swift init 在 objective-C 中不可见

转载 作者:IT王子 更新时间:2023-10-29 05:08:27 27 4
gpt4 key购买 nike

我正在尝试在 Swift 中创建 init 函数并从 Objective-C 创建实例。问题是我在 Project-Swift.h 文件中没有看到它,并且在初始化时我无法找到该函数。我有一个定义如下的函数:

public init(userId: Int!) {
self.init(style: UITableViewStyle.Plain)
self.userId = userId
}

我什至尝试放置 @objc(initWithUserId:) 并且我再次遇到同样的错误。还有什么我想念的吗?如何让构造函数对 Objective-C 代码可见?

我阅读了以下内容:

https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Initialization.html

https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/interactingwithobjective-capis.html

How to write Init method in Swift

How to define optional methods in Swift protocol?

最佳答案

您看到的问题是 Swift 无法桥接可选值类型——Int 是一种值类型,因此 Int! 无法桥接。可选引用类型(即任何类)正确桥接,因为它们在 Objective-C 中始终可以是 nil。您的两个选择是使参数成为非可选参数,在这种情况下,它将作为 intNSInteger 桥接到 ObjC:

// Swift
public init(userId: Int) {
self.init(style: UITableViewStyle.Plain)
self.userId = userId
}

// ObjC
MyClass *instance = [[MyClass alloc] initWithUserId: 10];

或者使用可选的 NSNumber?,因为它可以桥接为可选值:

// 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 也是可选参数,否则您将以这种方式为潜在的运行时崩溃做好准备。

关于objective-c - swift init 在 objective-C 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470771/

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