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

Swift报错:Binary operator '/'无法应用于Int和Double类型操作数,求修复

Fixing "Binary operator '/' cannot be applied to operands of type 'Int' and 'Double'" in Swift

Hey there! Let's get that Swift error sorted out for you. The issue you're hitting comes down to Swift's strict type safety—you can't perform arithmetic operations between mismatched numeric types (like Int and Double) directly. Your amountPaid is an integer, but you're trying to divide it by 100.0 (a double), which triggers the error. On top of that, your original ternary operator was mixing Int and Double return values, which would cause another type mismatch.

Here are two clean, targeted fixes for your code:

Option 1: Convert the Int to Double (for decimal precision)

This is the right choice if you want a decimal result (e.g., 150 becomes 1.5). Convert amountPaid to a Double first so both operands match, then wrap the result in an NSNumber to align with your function's return type:

var amountPaid: Int = 0 

func decimalNumber() -> NSNumber? {
    return amountPaid == 0 ? NSNumber(value: 0) : NSNumber(value: Double(amountPaid) / 100.0)
}

Option 2: Integer division (if you don't need decimals)

If you only care about whole number results (e.g., 150 becomes 1 instead of 1.5), you can convert the double divisor to an Int instead. Note this truncates any decimal part:

var amountPaid: Int = 0 

func decimalNumber() -> NSNumber? {
    return amountPaid == 0 ? NSNumber(value: 0) : NSNumber(value: amountPaid / 100)
}

Quick breakdown of the fix

In your original code, the ternary operator tried to return either an Int (0) or a Double (the division result), which created a second type mismatch. By wrapping both branches in NSNumber(value:), we ensure the function always returns the correct type.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:38:56