如何在三元条件运算符中使用Optional变量? [英] How do you use the Optional variable in a ternary conditional operator?

查看:104
本文介绍了如何在三元条件运算符中使用Optional变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Optional变量与三元条件运算符一起使用,但是会引发以下错误: optional不能用作布尔值。我在做什么错了?

  var str1:字符串? 
var myBool:Bool
myBool = str1吗? true:false


解决方案

您不能将字符串值分配给bool但是您可以像这样检查str1是否为nil:

  myBool = str1!= nil吗? true:false 
print(myBool)

由于str1为空,因此将打印false。 / p>

I want to use an Optional variable with the ternary conditional operator but it is throwing error this error: optional cannot be used as boolean. What am I doing wrong?

var str1: String?
var myBool:Bool
myBool = str1 ? true : false

解决方案

You can not assign string value to bool but You can check it str1 is nil or not like this way :

myBool = str1 != nil ? true : false
print(myBool)

It will print false because str1 is empty.

这篇关于如何在三元条件运算符中使用Optional变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆