问题描述
我不知道如何使用AutoreleasingUnsafePointer.我有以下代码:
I don't know how to use the AutoreleasingUnsafePointer. I have the following code:
var myString: AutoreleasingUnsafePointer<NSString?>
myScanner.scanUpToCharactersFromSet(NSCharacterSet.newlineCharacterSet(), intoString: myString)
现在,我应该怎么做才能从"myString"中获取字符串?我知道它可以为nil,但是我想不出一种方法来获取字符串值,以防它不是nil.而且,Swift解包技术仅适用于Optional类型.
Now, what should I do to get the string from 'myString'? I know it can be nil, but I couldn't figure out a way to get the string value in case it wasn't nil. And the Swift unwrapping technique just only works with the Optional type.
谢谢!
推荐答案
如果将 scanUpToCharactersFromSet
的第二个参数声明为自动释放不安全指针,即 AutoreleasingUnsafePointer< NSString?>
您应该能够在不显式创建指针的情况下调用函数.Swift可让您在 NSString?
变量上使用&
运算符来生成自动释放的不安全指针,如下所示:
If the second parameter of scanUpToCharactersFromSet
is declared as autoreleasing unsafe pointer, i.e. AutoreleasingUnsafePointer<NSString?>
you should be able to invoke your function without making a pointer explicitly. Swift lets you use &
operator on an NSString?
variable to produce an autoreleasing unsafe pointer, like this:
var str : NSString? = nil
myScanner.scanUpToCharactersFromSet(NSCharacterSet.newlineCharacterSet(), intoString:&str)
这将为您提供 str
作为正常"可选的 NSString
,您可以使用常规的解包运算符对其进行解包.
This would give you str
as a "normal" optional NSString
, which you can unwrap using the regular unwrapping operators.
这篇关于Swift:如何从AutoreleasingUnsafePointer< NSString"中获取值?从NSScanner?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!