简体   繁体   English

串? 不能转换为“ NSString”

[英]String? is not convertible to 'NSString'

I'm following an Apple WatchKit course on Udemy, in which I create an currency conversion type app. 我正在学习有关Udemy的Apple WatchKit课程,在其中我将创建一个货币换算类型的应用程序。 The following syntax works for the gentleman in the video, but gives me an error: 以下语法适用于视频中的绅士,但给我一个错误:

func parser(parser: NSXMLParser, foundCharacters string: String?) {
....

currencyConversions[getCurrency] = (string as NSString).doubleValue

He states that we need to first convert this object into an NSString, and then convert it into a double. 他指出,我们需要先将此对象转换为NSString,然后将其转换为double。 However, I get the following error: 但是,出现以下错误:

String? 串? is not convertible to 'NSString' 不能转换为“ NSString”

Perhaps he's using a newer version of Swift/Xcode? 也许他正在使用Swift / Xcode的较新版本? How can I fix this? 我怎样才能解决这个问题?

This works with Xcode 6.4 and Xcode 7.1.1 : 这适用于Xcode 6.4Xcode 7.1.1

Since s is an Optional String , you need to safely unwrap it before casting it as an NSString . 由于sOptional String ,因此在将其强制转换为NSString之前,您需要安全地将其解包。 Use the nil coalescing operator ?? 使用nil合并运算符 ?? to do that: 要做到这一点:

currencyConversions[getCurrency] = ((string ?? "") as NSString).doubleValue

NSString has a constructor that composes it from an ordinary string. NSString具有一个构造函数,该构造函数由普通字符串组成。 Try calling it from NSString(string!), and hopefully then it should work! 尝试从NSString(string!)调用它,希望它应该能工作!

You need to unwrap the string object before casting it. 您需要先解开字符串对象,然后再投射它。 Do not forget to check for nil value for optional object before unwrapping. 展开包装前,请不要忘记检查可选对象的nil值。

if (string != nil){
   currencyConversions[getCurrency] = (string! as NSString).doubleValue
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “ [String]”不可转换为“ [NSString]” - '[String]' is not convertible to '[NSString]' Swift:NSString无法转换为“字符串” - Swift: NSString not convertible to 'String' Swift 3 '[UIApplicationLaunchOptionsKey : Any]? 不可转换为 '[String : NSString]' - Swift 3 '[UIApplicationLaunchOptionsKey : Any]?' is not convertible to '[String : NSString]' “串?' 不能转换为'NSString'“(Xcode 7迁移后) - “String?' is not convertible to 'NSString'” (after Xcode 7 migration) 'NSString的!' 不能转换为'String'; 您是要使用“ as!”吗? 强迫垂头丧气? - 'NSString!' is not convertible to 'String'; did you mean to use 'as!' to force downcast? Swift-'PFObject无法转换为NSString' - Swift - 'PFObject is not convertible to NSString' Swift 2:AnyObject? 不能转换为NSString - Swift 2: AnyObject? is not convertible to NSString 的NSString? 不能转换为'StringLiteralConvertible'&?! 在斯威夫特 - NSString? is not convertible to 'StringLiteralConvertible' & ?! in Swift PFFile? 不可转换为'StringLiteralConvertible''AnyObject'不可转换为'String' - PFFile? is not convertible to 'StringLiteralConvertible' 'AnyObject' is not convertible to 'String' AnyObject不能转换为String - AnyObject is not convertible to String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM