替换数组中的元素 - 代码工作,除非2位或更多位数相同 - swift [英] Replace elements in array - code working unless 2 or more digits are the same - swift

查看:753
本文介绍了替换数组中的元素 - 代码工作,除非2位或更多位数相同 - swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找出一种方法将数组中元素的值更改为swift中的某个值。



我想用一个值替换值不同的价值如下:



- 0 - > 0

- 1 - > 4

- 2 - > 3

- 3 - > 2

- 4 - > 1

- 5 - > 0

- 6 - > 1

- 7 - > 3

- 8 - > 2

- 9 - > 1



我有一组6个数字,例如123456,我想用相应的数字单独替换每个数字,如上所示。



我想出了大部分要做的事情但是如果有2个相同的数字就会失败。谁能告诉我我错过了什么?例如,如果我的数组是[1,2,3,4,5,6],则新数组将为[4,1,3,0,2,4]。它在原始数组为[5,5,5,5,5,5]的示例中失败,因为新数组为[0]。





如果有人知道怎么做,我会很感激。



谢谢!



我的尝试:



I'm trying to figure out a way to change the value of element in array to certain value in swift.

I want to replace the value with a different value as follows:

- 0 -> 0
- 1 -> 4
- 2 -> 3
- 3 -> 2
- 4 -> 1
- 5 -> 0
- 6 -> 1
- 7 -> 3
- 8 -> 2
- 9 -> 1

I have a group of 6 numbers, for example 123456, and I want to individually replace each digit with the corresponding digit as shown above.

I figured out what to do for the most part but it fails if there are 2 of the same digits. Can anyone tell me what I'm missing? For example, if my array is [1, 2, 3, 4, 5, 6] the new array will be [4, 1, 3, 0, 2, 4]. It fails in the example where the original array is [5, 5, 5, 5, 5, 5] because the new array is [0].


If anyone has an idea how to do this I would appreciate it.

Thank you!

What I have tried:

var elements = [1, 2, 3, 4, 5, 6]
for (i, digit) in elements.enumerated() {
    if digit == 1 {
        elements[i] = 4
    } else if digit == 2 {
        elements[i] = 3
    } else if digit == 3 {
        elements[i] = 2
    } else if digit == 4 {
        elements[i] = 1
    } else if digit == 5 {
        elements[i] = 0
    } else if digit == 6 {
        elements[i] = 4
    } else if digit == 7 {
        elements[i] = 3
    } else if digit == 8 {
        elements[i] = 2
    } else if digit == 9 {
        elements[i] = 1
    } else if digit == 0 {
        elements[i] = 0
    }

}

推荐答案

我刚才发现了问题。这是由于我之后的代码将此数组转换为整数。当5是数组中的第一个数字时,此代码将其更改为0,因此当它转换为整数时,0被删除。我通过转换为字符串来修复它。
I just figured out the problem. It was due to code I had after this that converted this array to an integer. When 5 was the first number in the array, this code changed it to a 0 so when it was then converted into an integer, the 0 was dropped. I fixed it by converting to a string instead.


这篇关于替换数组中的元素 - 代码工作,除非2位或更多位数相同 - swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆