You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:如何判断Double类型变量是否为空?解决空值比较报错

解决Swift中非可选Double无法判断空值的问题

你的choosenLatitude和choosenLongitude是非可选Double类型,这类变量永远不可能等于nil,所以编译器提示“Comparing non-optional value of type 'Double' to 'nil' always returns false”。下面是两种可行的解决办法:

方案一:将变量改为可选Double类型(推荐)

把这两个变量的类型从Double改成Double?,让它们默认处于未赋值的nil状态,用户选择位置后再给它们赋值。

修改变量定义

var choosenLatitude: Double?
var choosenLongitude: Double?

修改addLocation方法逻辑

@IBAction func addLocation(_ sender: UIButton) {
    // 保存添加的位置及数据
    if nameText.text?.isEmpty ?? true {
        makeAlert(tıtleInput: "Error", messageInput: "名称不能为空!")
    } else if commentText.text?.isEmpty ?? true {
        makeAlert(tıtleInput: "Error", messageInput: "评论不能为空!")
    } else if choosenLatitude == nil || choosenLongitude == nil {
        makeAlert(tıtleInput: "Error", messageInput: "请选择您的位置")
    } else {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        
        let newPlace = NSEntityDescription.insertNewObject(forEntityName: "Places", into: context)
        
        newPlace.setValue(nameText.text, forKey:"title")
        newPlace.setValue(commentText.text, forKey: "subtitle")
        // 已通过判断确认非nil,可安全解包
        newPlace.setValue(self.choosenLongitude!, forKey: "longitude")
        newPlace.setValue(self.choosenLatitude!, forKey: "latitude")
        newPlace.setValue(UUID(), forKey: "id")
        
        // 补充CoreData保存逻辑
        do {
            try context.save()
            // 这里可以添加保存成功后的操作,比如返回前页
        } catch {
            print("保存失败:\(error.localizedDescription)")
        }
    }
}

这种方式完全符合Swift的可选类型设计逻辑,能清晰表达“变量可能未被赋值”的状态,是最合理的解决方案。

方案二:用特殊标记值判断(仅当无法修改变量类型时使用)

如果不能修改变量的可选状态,可以给它们设置一个业务场景中不可能出现的初始值,比如Double.nan(非数字,有效的经纬度不会是NaN),通过判断这个值来识别未选择状态。

修改变量定义

var choosenLatitude: Double = .nan
var choosenLongitude: Double = .nan

修改判断逻辑

// 替换原有的nil判断代码
else if choosenLatitude.isNaN || choosenLongitude.isNaN {
    makeAlert(tıtleInput: "Error", messageInput: "请选择您的位置")
}

这种方式需要确保业务流程中不会产生这个特殊值,否则会出现误判,因此仅作为备选方案。


内容的提问来源于stack exchange,提问作者Bayram Yalav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:35:28