将NSRangePointer从Objective-C翻译为Swift [英] Translate NSRangePointer from Objective-C to Swift

查看:847
本文介绍了将NSRangePointer从Objective-C翻译为Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将一些Objective-C代码翻译成Swift时遇到错误。

I'm getting an error when translating some Objective-C code to Swift.

我正在使用 - 属性:atIndex:effectiveRange: NSAttributedString 并且有关于 effectiveRange 参数,这是一个 NSRangePointer

I'm using - attribute:atIndex:effectiveRange: of NSAttributedString and having an error concerning the effectiveRange parameter, which is an NSRangePointer.

Objective-C:

Objective-C:

NSRange range;
id value = [self.textanalyze
                      attribute:attribute
                        atIndex:index
                 effectiveRange:&range]

Swift:

var range : NSRange?
var value : Any = self.textanalyze.attribute(attributes,
                      atIndex: index,
               effectiveRange: &range)   

我在& range 附近出错。

推荐答案

您需要打开范围。

此外,您需要初始化范围。否则,这将使您的程序崩溃。

Also, you need to initialize range. Otherwise, this will crash your program.

var range : NSRange? = NSMakeRange(0, 1)
self.textanalyze.attribute(attributes, atIndex: index, effectiveRange: &range!)

或者,如果您不想打开您的范围(可能是零),请重写您的函数:

Or, if you don't want to unwrap your range (it might be nil), rewrite your function like this:

var range : NSRange?
doSomethingWithRangePointer(&range)

func doSomethingWithRangePointer(range : UnsafeMutablePointer<NSRange?>) {
    // Do stuff
}

但您可能不需要首先将您的范围设为可选(想想,范围是否需要为零?如果没有,那么它不需要是可选的。),在这种情况下,只需像这样初始化范围就可以了:

But you may not have needed to make your range an optional in the first place (think, does range ever need to be nil? If not, then it doesn't need to be optional.), in which case, just initializing range like this will work:

var range = NSMakeRange(0, 1)

这篇关于将NSRangePointer从Objective-C翻译为Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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