看看这段代码,如果有什么我可以改变,请告诉我

时间:2014-10-05 13:24:29

标签: ios swift xcode6 swift-playground

昨天我问了一个问题并得到了一个很棒的答案,解决了我的大部分问题。我试图将特定数值与以12为增量分配的11种颜色配对,并将每12次增量重复的形状配对。

ex: 0:black:circle, 1:black:cross, 2:black:star...12
    0:brown:circle, 1:brown:cross, 2:brown:star...12
    0:red:circle,   1:red:cross,   2:red:star...12

依此类推,直到每个数字分配给一个颜色和形状。下面的代码执行此操作。但它以我没想到的方式做到了,输出低于。

struct ValueStruct {
var numValue: Int
var color: String
var shape: String

init(numValue: Int, color: String, shape: String) {
    self.numValue = numValue
    self.color = color
    self.shape = shape
  }
}

var startingNumValue = 0
let colorsArray = ["Black", "Brown", "Red", "Yellow", "Orange", "Green", "Grey", "Blue", "Purple", "Pink", "White"]
let shapesArray = ["Circle", "Cross", "Star", "Rectangle", "Triangle", "Square", "Heart", "Crown", "Line", "Diamond", "Ellipse", "Sun"]


var containingArray:[ValueStruct] = []

for colorItems in colorsArray {
for shapeItems in shapesArray {
    containingArray.append(ValueStruct(numValue: startingNumValue, color: colorItems, shape: shapeItems))
    startingNumValue += 1
}

这就是操场上的输出看起来像这样的问题。

1)这是最简洁的方法吗?正常循环的输出通常都在一个窗口中,并且看起来这是以一种停止的方式循环而不是从一个窗口开始。直到完成。

2)有没有办法设置startingNumValue的上限我只需要它去128,我担心以后可能出现的错误。

3)最后这在游乐场中工作正常但是从常规项目中的for colorItems in colorsArray行开始它会产生Statements are not allowed at the top level错误,有关处理该问题的最佳方法的任何建议吗? enter image description here

2 个答案:

答案 0 :(得分:2)

我添加了一个if语句,将数组限制为128个项目。在项目中,除了变量赋值之外的代码需要在函数中。试试这个:

import UIKit

struct ValueStruct {
    var numValue: Int
    var color: String
    var shape: String

    init(numValue: Int, color: String, shape: String) {
        self.numValue = numValue
        self.color = color
        self.shape = shape
    }
}

class ViewController: UIViewController, UITableViewDelegate {

    var startingNumValue = 0
    let colorsArray = ["Black", "Brown", "Red", "Yellow", "Orange", "Green", "Grey", "Blue", "Purple", "Pink", "White"]
    let shapesArray = ["Circle", "Cross", "Star", "Rectangle", "Triangle", "Square", "Heart", "Crown", "Line", "Diamond", "Ellipse", "Sun"]
    var containingArray:[ValueStruct] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        for colorItems in colorsArray {
            for shapeItems in shapesArray {
                if startingNumValue < 128 {
                    containingArray.append(ValueStruct(numValue: startingNumValue, color: colorItems, shape: shapeItems))
                    startingNumValue += 1
                }
            }
        }
        println(startingNumValue)
    }
}

答案 1 :(得分:1)

另一种选择是使用单个for循环,并使用模数运算从数组中进行选择,如下所示:

for i in 0..<128 {
    let colorIndex = i % (colorsArray.count)
    let shapesIndex = i / colorsArray.count
    containingArray.append(ValueStruct(numValue: i, color: colorsArray[colorIndex], shape: shapesArray[shapesIndex]))
}

但要坚持这一点,你需要注意你不要超越shapesArray的范围。