nil coalescing inside dictionary index using swift

123 Views Asked by At

Im trying to assign a value to dictionary key with optional value from textfield textFieldOne.text! and textFieldTwo.text!, but Xcode throws build error.

let variable = [
        "keyOne": textFieldOne.text ?? "",
        "keyTwo": textFieldTwo.text ?? ""
] as [String : Any]

Build Failed as The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

2

There are 2 best solutions below

2
Shehata Gamal On BEST ANSWER

You don't have to as default of text property is ""

let variable = [
    "keyOne": textFieldOne.text!,
    "keyTwo": textFieldTwo.text!
 ] 

Check https://developer.apple.com/documentation/uikit/uitextfield/1619635-text

0
PGDev On

You can create the Dictionary like,

var variable = [String:Any]()
variable["keyOne"] = textFieldOne.text
variable["keyTwo"] = textFieldTwo.text