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
.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With