0

Why do I get errors on Optional variable declaration?

var s: Int? = 12 print(s) I get like 5 errors back and no output. But removing the `?`, I get fully functioning code. test1.swift:3:7: warning: expression implicitly coerced from 'Int?' to Any print(s) ^ test1.swift:3:7: note: provide a default value to avoid this warning print(s) ^ ?? <#default value#> test1.swift:3:7: note: force-unwrap the value to avoid this warning print(s) ^ ! test1.swift:3:7: note: explicitly cast to Any with 'as Any' to silence this warning print(s) ^ as Any Optional(12)

11th Aug 2019, 3:54 AM
Jacob Schneider
Jacob Schneider - avatar
1 Antwort
+ 1
Hello! You are not actually getting any errors. You are simply getting warnings from the compiler that the calue that your are printing out to the console is optional so you should unwrap it. Either you bang it, or you do it the safer way by either using if-let, guard-let or nil coalescing
9th Jul 2021, 3:35 PM
Pawel Zabinski
Pawel Zabinski - avatar