2017-09-14 63 views
0

从Swift 2.x迁移到Swift 3时,出现错误“'String!'是不可转换为'字符串'“在线至极012Swift 2.x swift 3,XCode抱怨错误:'String!'不能转换为'String'

self.cartItemController.textCombinationsToDisplayInCart[pCombinationsPickerView.combinationName as String]=combinationValue["Name"] 

是否有任何一个想法如何纠正?

func setTextCombinationsToDisplayInCart(_ pCombinationsPickerView:CombinationsPickerView,pRow:Int) 
{ 
    var combinationValue:[NSString : NSObject]=pCombinationsPickerView.combinationValues[pRow] as! [NSString : NSObject] 
    if(pCombinationsPickerView.combinationID != 1)//Personnalisation 
    { 
     self.cartItemController.textCombinationsToDisplayInCart[pCombinationsPickerView.combinationName as String]=combinationValue["Name"] 
    } 
} 

回答

1

的问题是,myVar as String回报String?代替String

如果您确定此转换始终有效,您可以改为使用myVar as! String

但是,如果您担心强制类型转换可能会返回nil可选,您可以尝试使用guard语句。

+0

我用[pCombinationsPickerView.combinationName as!替换:[pCombinationsPickerView.combinationName as String]字符串],但现在它警告:“从'字符串强制转换!'到'字符串'总是成功的,你是否想用'as'?而Xcode提议用'as'替换。按'as'... – Zipette

+0

问题可能出现在右侧,'combinationValue [“Name”]'是'NSString',你需要使用'as'转换为 –

+0

非常感谢,解决了这个错误:我通过self.cartItemController.textCombinationsToDisplayInCart [pCombinationsPickerView.combinationName as NSString] = combinationValue [“Name”]替换self.cartItemController.textCombinationsToDisplayInCart [pCombinationsPickerView.combinationName as String] = combinationValue [“Name”] – Zipette