Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate NSRangePointer from Objective-C to Swift

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

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

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)   

I got an error near &range.

like image 236
daniyal yousuf Avatar asked Sep 13 '14 16:09

daniyal yousuf


2 Answers

You need to unwrap the 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)
like image 136
michaelsnowden Avatar answered Nov 14 '22 19:11

michaelsnowden


let a = sizeof(NSRange)
let objRangePtr:NSRangePointer = NSRangePointer.alloc(a) //alloc memory
objLayoutManager.characterRangeForGlyphRange(range, actualGlyphRange:objRangePtr)
let objRange = objRangePtr.move() //gain the value and dealloc()
like image 44
zHeng Avatar answered Nov 14 '22 21:11

zHeng