Swift新手在这里尝试设置数据验证功能,但我的代码生成以下错误:“二元运算符'>'不能适用于两个'双?'操作数“
func validateDouble(text: String) -> Bool {
var result = false
// test input to see if it is a positive Double once text is converted
if Double(text) > 0.0 {
result = true
}
}
我很难过,希望得到任何帮助。
谢谢,
NAS
答案 0 :(得分:2)
因为当你将字符串转换为Double类型时它返回可选值,所以它可能是零或不是。这就是为什么不能与精确值进行比较的原因。试试这种方式。
{
process:[
{
pid:'1990',
user:'alex',
pr:'20',
ni:'0',
virt:'1560516',
res:'90656',
shr:'21864',
s:'S',
cpu:'6.1',
mem:'12.5',
time:'13:46.58',
command:'cinnamon'
},
{
pid:'5381',
user:'alex',
pr:'20',
ni:'0',
virt:'929508',
res:'119792',
shr:'8132',
s:'S',
cpu:'6.1',
mem:'16.5',
time:'11:14.11',
command:'firefox'
},
{
pid:'0245',
user:'alex',
pr:'20',
ni:'0',
virt:'24948',
res:'1508',
shr:'1056',
s:'R',
cpu:'6.1',
mem:'0.2',
time:'0:00.02',
command:'top'
},
{
pid:'1',
user:'root',
pr:'20',
ni:'0',
virt:'37352',
res:'5688',
shr:'488',
s:'S',
cpu:'0.0',
mem:'0.8',
time:'0:04.93',
command:'init'
},
{
pid:'2',
user:'root',
pr:'20',
ni:'0',
virt:'0',
res:'0',
shr:'0',
s:'S',
cpu:'0.0',
mem:'0.0',
time:'0:00.07',
command:'kthreadd'
},
{
pid:'3',
user:'root',
pr:'20',
ni:'0',
virt:'0',
res:'0',
shr:'0',
s:'S',
cpu:'0.0',
mem:'0.0',
time:'0:54.23',
command:'ksoftirqd/0'
},
{
pid:'4',
user:'root',
pr:'20',
ni:'0',
virt:'0',
res:'0',
shr:'0',
s:'S',
cpu:'0.0',
mem:'0.0',
time:'0:00.00',
command:'kworker/0:0'
}
],
task:{
total:194,
running:1,
sleeping:193,
stopped:0,
zombie:0
},
cpu:{
user:0.9,
system:3.1,
ni:0.1,
'idle':95,
wa:0.3,
hi:0.6,
si:0,
st:0
},
ram:{
total:727308,
used:664028,
free:63280,
buffers:7600
},
swap:{
total:753660,
used:309516,
free:444144,
cachedMem:187424
}
}
答案 1 :(得分:1)
你需要检查确保转换后的值不是nil,这应该可以解决问题:
func validateDouble(text: String) -> Bool {
// test input to see if it is a positive Double once text is converted
guard let value = Double(text), value > 0.0 else { return false }
return true
}
答案 2 :(得分:1)
试试这个
if let doubleValue = Double(text), doubleValue > 0.0 {
result = true
}