请帮助重拍这个
if let field = parent_obj?.getFieldForCode(code) { if let stored_value = field["value"] as? String {单行中的可选链接语法。 我试着这样做:
let stored_value = parent_obj?.getFieldForCode(code)?["value"] as? String并得到一个错误:
Type 'String' does not conform to protocol 'NSCopying'这是我的函数头:
func getFieldForCode(code: String) -> NSDictionary?可能吗? 我问它,因为任何时候我使用NSArrays和NSDictionaries我的代码看起来很糟糕:
if let code = self.row_info["code"] as? String { if let value_field = self.row_info["value_field"] as? String { if let field = parent_obj?.getFieldForCode(code) { if let stored_value = field["value"] as? String { if let fields = self.fields_set{ if let current_value = fields[indexPath.row][value_field] as? String {有什么建议吗?
Please help to remake this
if let field = parent_obj?.getFieldForCode(code) { if let stored_value = field["value"] as? String {into optional chaining syntax in single line. I tried to do it like this:
let stored_value = parent_obj?.getFieldForCode(code)?["value"] as? Stringand got an error:
Type 'String' does not conform to protocol 'NSCopying'This is my function header:
func getFieldForCode(code: String) -> NSDictionary?Is it possible? I ask it because any time I work with NSArrays and NSDictionaries my code looks terrible:
if let code = self.row_info["code"] as? String { if let value_field = self.row_info["value_field"] as? String { if let field = parent_obj?.getFieldForCode(code) { if let stored_value = field["value"] as? String { if let fields = self.fields_set{ if let current_value = fields[indexPath.row][value_field] as? String {Any advices?
最满意答案
你不能将它直接转换为String因为你从NSDictionary提取它,就像错误所说的那样, String不符合NSCopying 。 但是, String桥接到NSString , NSString符合NSCopying 。 所以,通过一点点演员/桥接技巧,你可以让它像这样工作:
let stored_value: String? = parent_obj?.getFieldForCode(code)?["value"] as? NSString注意:如果你在可选的绑定中使用它(它看起来像你想要的那样),不要忘记放弃? 来自stored_value的类型声明:
if let stored_value: String = parent_obj?.getFieldForCode(code)?["value"] as? NSString { /* ... */ }You can't cast it directly to a String because you're pulling it from an NSDictionary and, like the error says, String doesn't conform to NSCopying. However, String is bridged to NSString, and NSString does conform to NSCopying. So, with a little bit of casting/bridging trickery, you can make it work like this:
let stored_value: String? = parent_obj?.getFieldForCode(code)?["value"] as? NSStringNote: If you're using this in an optional binding (which it looks like you want to), don't forget to drop the ? from stored_value's type declaration:
if let stored_value: String = parent_obj?.getFieldForCode(code)?["value"] as? NSString { /* ... */ }更多推荐
发布评论