使用Swift,我试图在应用程序的文本视图中输入一个数字列表,并通过提取成绩计算器的每个数字来创建此列表的总和。此外,用户输入的值的数量也会发生变化。示例如下所示:
Using Swift, I'm trying to take a list of numbers input in a text view in an app and create a sum of this list by extracting each number for a grade calculator. Also the amount of values put in by the user changes each time. An example is shown below:
字符串:98,99,97,96 ... 试图得到:98 + 99 + 97 + 96。 ..
String of: 98,99,97,96... Trying to get: 98+99+97+96...
请帮忙! 谢谢
Please Help! Thanks
推荐答案
使用 reduce 来总结 Int 的数组。
Use reduce to sum up the array of Int. let input = " 98 ,99 , 97, 96 " let values = inputponents(separatedBy: ",").flatMap { Int($0.trimmingCharacters(in: .whitespaces)) } let sum = values.reduce(0, +) print(sum) // 390
更多推荐
字符串转换为Int并将逗号替换为加号
发布评论