简体   繁体   English

字符串与nil对象快速连接

[英]string concatenate with nil object in swift

I am trying find string value from coredata entity which some time return either string value or nil value. 我正在尝试从coredata实体中查找字符串值,该实体有时会返回字符串值或nil值。 I have to join that value with another string but when its return nil application crashed my code snippet 我必须将该值与另一个字符串连接起来,但是当它的返回nil应用程序崩溃时,我的代码片段

let objtest = (TblObjectValue.findOrCreate(["objectId":dicCurrent.valueForJSON("Id")]) as TblObjectValue)
tablecell.lblTitle?.text = "Value: "+objtest.displayValue! 

Where TblObjectValue is NSManagedObject and objectId(NSString) and displayValue(NSString) are attribute of TblObjectValue entity application crash if displayValue is null 如果displayValue为null,则其中TblO​​bjectValue是NSManagedObject,objectId(NSString)和displayValue(NSString)是 TblO​​bjectValue实体application crash if displayValue is null 属性

i want it in one line beacuse i used following code many time in my project i want it in one line因为我在项目中多次使用以下代码

tablecell.lblTitle?.text = (dicCurrent.valueForJSON("CardLabel") as? String)!+": "+(TblObjectValue.findOrCreate(["objectId":dicCurrent.valueForJSON("Id")]) as TblObjectValue).displayValue! 

Check it before do anything: 在执行任何操作之前先检查一下:

if objtest.displayValue != nil {
  tablecell.lblTitle?.text = "Value: "+objtest.displayValue!
}

Doesn't

tablecell.lblTitle?.text = "Value: "+ (objtest.displayValue ?? "")

do the trick? 绝招?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM