找到可扩展的解决方案以在Swift中从数组中打印数据
我有一个从1到100开始的数组然后,“ AB”都可以除外,如果将来我想添加数字8应该打印为“ C”,并由4& 8应该打印“ AC”,按5& 8应该打印“ bc”,如果这三个则为“ ABC”
所需的输出:
1
2
3
A
B
6
7
C
9
B
11
AB
13
14
...
我写了这本书,
for number in 1...100 {
if number.isMultiple(of: 4) && !number.isMultiple(of: 5){
print("A"
} else if !number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("B")
} else if number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("AB")
} else {
print(number)
}
}
请提供一个可扩展的解决方案,以保持添加If-Else不是一个不错的选择。
I have an array starting from 1 to 100 and I have to print element if the number is divisible by 4 it should print the letter "A" and if the number is divisible by 5 it should print the letter "B" and if it is divisible by both then "AB" I want to make a scalable solution if in future I want to add number divisible by 8 should print "C" and divisible by 4 & 8 should print "AC", by 5&8 should print "BC" and if all three then "ABC"
desired output:
1
2
3
A
B
6
7
C
9
B
11
AB
13
14
...
I wrote this
for number in 1...100 {
if number.isMultiple(of: 4) && !number.isMultiple(of: 5){
print("A"
} else if !number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("B")
} else if number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("AB")
} else {
print(number)
}
}
Please provide a scalable solution to keep adding If-else is not a good option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您非常接近,但您不需要其他条件。如果字符串与另一个条件匹配,只需将字符添加到字符串中:
使用字典存储字符:
请注意,字典是无序的集合。如果您需要对字符进行排序,则需要在迭代其键值对之前通过其值对其值进行排序:
You were pretty close but you don't need the else conditions. Just add the character to the string if it matches another condition:
Using a dictionary to store the characters:
Note that dictionary is an unordered collection. If you need the characters to be sorted you would need to sort the dictionary by its values before iterating its key value pairs:
在这里,它不是使用IF-Else,而是可以在需要的结果时添加
::
如果您只需要[任何]类型,然后
Here it is, instead of using if-else, you can just add up whenever you need
Result::
if you just want [Any] type then just