![]() The point of using a ? b is that a is optional, and the docs say ? unwraps a if it isn't nil, so if you let Swift infer the result type, b and the result are the same "optionalness". I suppose to be explicit, you should write it as: let j: Int = Int(s ? "0") ? 0Īfter thinking about it some more, it isn't strange it works for the same reason the s ? "0" part of our simple example works (where s is optional but "0" is not). ![]() Which is kind of strange, because Int(s ? "0") returns an optional, but 0 is not optional, and Swift creates j as non-optional and doesn't complain. The following works ONLY if the optional string really contains an integer: let j = Int(s ? "0")!ĮDIT: The following works no matter what is in the optional string: let j = Int(s ? "0") ? 0 Then we converted the string to an integer by using the toInt() function and stored the result in num variable. ![]() That second line won't compile "Binary operator '?' cannot be applied to operands of type 'String?' and 'Int'. No you have converted z to int and store the result in sum so sum is the int value of z but z is still a variable of type String.What you are trying to do here is the same as multiplying sum by two. In the above code, we have declared the two variables a with the string data type and num with the integer data type.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |