Swift Optional Int(Int?)是否可以通过桥接暴露给Objective-C? [英] Can a Swift Optional Int (Int?) be exposed to Objective-C via bridging?

查看:107
本文介绍了Swift Optional Int(Int?)是否可以通过桥接暴露给Objective-C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从基于Obj-C的框架派生的Swift类中(但也可以很容易地成为具有@objc属性的Swift类),我声明了两个存储的属性:

Within a Swift class derived from an Obj-C based framework (but could just as easily be a Swift class with an @objc attribute) I declare two stored properties:

var optInt: Int?
var optString: String?

只有optString通过生成的-Swift.h标头公开给Obj-C.

Only optString is being exposed to Obj-C via the generated -Swift.h header.

字符串?之所以可以认为是很好的,是因为它使用一个可以为nil的NSString对象公开,因此桥接具有一种不表示任何值的方法.

String? is presumably fine because it is exposed using an NSString object which can be nil, so the bridging has a way to represent no value.

如果我删除了?从optInt来看,它使用NSInteger类型公开,因此我可以看到,对于非可选整数,它避免了对象,并将值类型桥接到值类型,但这从字面上意味着是Int吗?不能暴露?

If I remove the ? from optInt it's exposed with an NSInteger type, so I can see that for non-optional integers it avoids objects and bridges value type to value type, but does this literally mean that an Int? can't be exposed?

我似乎找不到任何明确表明是这种情况的文档.这里有不兼容的Swift功能的完整列表,这些功能不会出现在以下位置:

I can't seem to find any documentation that explicitly says this is the case. There is a whole list of incompatible Swift features here that this doesn't appear on: Using Swift from Objective-C

这里的用例是经典情况,要求传递一个数字ID,该数字ID可以合法地为零.在Swift之前的世界中,NSNumber和nil正是我实现此方法的方式,但是尝试将类迁移到Swift,然后专门因为这个原因而挂在Swift类中的Obj-C类型上,这感觉是错误的.

The use case here is the classic situation requiring the passing of a numeric ID which could legitimately be zero. In the pre-Swift world NSNumber and nil is exactly how I went about implementing this, but it just feels wrong to be trying to migrate a class to Swift but then hanging on to Obj-C types within the Swift class specifically for this reason.

我想我曾设想过一个Int?与Int会在后台作为NSNumber桥接的方式不同,Int可能将其nil值提供给Swift中可选的无值"元素.

I suppose I had envisaged that an Int? unlike Int would bridge as an NSNumber in the background, with its potentially nil value feeding the "has no value" element of the optional in Swift.

这里有什么我想念的吗?重申一下,可以通过桥接将Swift Optional Int(Int?)暴露给Objective-C吗?

Is there anything I'm missing here? To reiterate, can a Swift Optional Int (Int?) be exposed to Objective-C via bridging?

推荐答案

以下是上述解决方案的具体答案:

Here's a concrete answer for the solution described above:

private var _number: Int?
public var number: NSNumber? {
    get {
        return _number as NSNumber?
    }
    set(newNumber) {
        _number = newNumber?.intValue
    }
}

// In case you want to set the number in the init
public init(number: NSNumber?) {
    _number = number?.intValue
}

这篇关于Swift Optional Int(Int?)是否可以通过桥接暴露给Objective-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆