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

SwiftUI中字符串与整数拼接问题求助,JSON Int字段拼接实现

解决Swift中Int与字符串拼接的问题

你遇到的是Swift强类型特性导致的典型问题——Swift不允许直接将Int类型和String类型用+运算符拼接,不过有两种简单的解决方式:

方法1:将Int转换为String后拼接

直接用String()构造器把Int值转换成字符串,再和前缀文本拼接:

cost_for_two: "Avg Cost for two: " + String(i.restaurant.average_cost_for_two)

方法2:使用字符串插值(更推荐的Swift风格)

字符串插值是Swift里更简洁、可读性更高的写法,直接在字符串里通过\()嵌入Int值:

cost_for_two: "Avg Cost for two: \(i.restaurant.average_cost_for_two)"

修改后的完整代码片段

替换你原来的cost_for_two赋值部分即可:

for i in fetch.nearby_restaurants{
    DispatchQueue.main.async {
        self.datas.append(datatype(
            id: i.restaurant.id,
            name: i.restaurant.name,
            image: i.restaurant.thumb,
            rating: "Rating: " + i.restaurant.user_rating.aggregate_rating,
            cost_for_two: "Avg Cost for two: \(i.restaurant.average_cost_for_two)",
            webUrl: i.restaurant.url
        ))
    }
}

如果之后需要更复杂的格式(比如添加货币符号、千位分隔符),可以使用NumberFormatter来处理,但针对你当前的需求,上面两种方法完全够用啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:07:50