如何遍历Swift结构并设置每个对象的值?

时间:2015-10-26 19:10:03

标签: swift struct

我目前有以下结构,我想要做的是遍历每个变量并将其设置为随机整数(使用Int(arc4random_uniform(52)))。

有办法做到这一点吗?我试过搜索类似的问题,但是他们建议创建一个包含我的struct并迭代数组方式的数组,这似乎不能正常工作。

struct SevenCardStruct {
            var firstCardString: Int
            var secondCardString: Int
            var thirdCardString: Int
            var fourthCardString: Int
            var fifthCardString: Int
            var sixthCardString: Int
            var seventhCardString: Int
        }

1 个答案:

答案 0 :(得分:0)

如果不实现数组,一个选项是使用隐式成员初始值设定项

struct SevenCardStruct {
  var firstCardString: Int
  var secondCardString: Int
  var thirdCardString: Int
  var fourthCardString: Int
  var fifthCardString: Int
  var sixthCardString: Int
  var seventhCardString: Int
}

func random() -> Int
{
  return Int(arc4random_uniform(52))
}

let card = SevenCardStruct(firstCardString: random(), secondCardString: random(), thirdCardString: random(), fourthCardString: random(), fifthCardString: random(), sixthCardString: random(), seventhCardString: random())