Swift函数与数字变量

时间:2018-05-08 12:52:37

标签: swift

如果我有4个变量:

var team1 = 0
var team2 = 0
var team3 = 0
var team4 = 0

有没有办法编写一个函数,输入一个整数,这将允许我做类似的事情

func AddPointsToTeam(TeamNumber: Int) {
 TeamX += 1
}

我知道我可以使用数组来做这个,并使用输入作为数组的索引,但有没有办法这样做?

4 个答案:

答案 0 :(得分:0)

很难说,因为不清楚你想要做什么......或者你会期待什么。

例如,我使用了字典。

var teamsDictionary:[String:Int] = ["team1":0,"team2":0,"team3":0,"team4":0]

print("Count of Team 1: \(teamsDictionary["team1"])") //prints 0
teamsDictionary["team1"] = 4
print("Count of Team 1: \(teamsDictionary["team1"])") //prints 4

此外,您也可以使用SetsArrays。查看文档以获得灵感https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

答案 1 :(得分:0)

在swift中创建函数时使用camel case,对变量也是如此。

  

您可以通过将inout关键字放在参数类型之前来编写输入输出参数。输入输出参数具有传递给函数的值,由函数修改,并传递回函数以替换原始值。

var rx = /[\r\n]+(?=(?:GET|PUT|POST|DELETE)\b)/gm;
var str = 'GET /bar\n{\n  "limit":  {\n     "foo": 1\n   }\n}\n\n\nGET /barfoo\n{\n  "limit": {\n     "foo": 1\n\n   }\n}\n\nGET /fuzz\n{\n  "limit": 1\n}';
var result = str.split(rx);
console.log(result);

答案 2 :(得分:0)

对于您的确切问题,是的,这是可能的。你想要这样做是非常不可能的,但是只要你把它放在NSObject的子类中并将所有内容标记为@objc就可以了,那么你可以使用Key-Value Coding

import Foundation

class League: NSObject {
    @objc var team1: Int = 0  // Fun-fact: If you fail to include @objc here
    @objc var team2: Int = 0  // it will compile fine, but it'll crash later.
    @objc var team3: Int = 0  // Using the ObjC runtime takes away many of the
    @objc var team4: Int = 0  // compiler protections that Swift offers.

    // This is an advanced technique that should almost never be used in Swift
    func addPointsToTeam(number: Int) {
        let key = "team\(number)"
        let oldValue = value(forKey: key) as! Int
        setValue(oldValue + 1, forKey: key)
    }
}

let league = League()
league.addPointsToTeam(number: 1)

但是使用KVC和手工制作的选择器几乎肯定不是你想要的工具。即使在通常使用KVC的ObjC中,像这样的手工制作选择器也是罕见且危险的,通常仅用于高级工具。

您想要的工具是一个数组。当您表示列表时,请勿使用四个变量。使用一个变量:

var teamScores = [0, 0, 0, 0]

func addPointsToTeam(number: Int) {
    teamScores[number] += 1
}

很快你会发现你有多个并行数组,如teamScoresteamNames。此时,您应该再次修复数据。和以前一样,不要使用多个变量:

struct Team {
    let name: String
    var score: Int
}

var teams = [Team(name: "Alices", score: 0), Team(name: "Bobs", score: 0)]

func addPointsToTeam(number: Int) {
    teams[number].score += 1
}

请注意,数组是0索引的。因此,如果您想要与“1,2,3,4”对齐,则需要根据需要减去或添加一个。

答案 3 :(得分:0)

解决这个问题的一种方法是为团队使用枚举,这样可以更清楚地使用该函数。

enum Team: Int {
  case team1 = 1
  case team2
  case team3
  case team4
}

struct TeamPoints {
  var team1 = 0
  var team2 = 0
  var team3 = 0
  var team4 = 0

  mutating func addPoint(forTeam team:Team) {
    switch team {
    case .team1:
      team1 += 1
    case .team2:
      team2 += 1
    case .team3:
      team3 += 1
    case .team4:
      team3 += 1
    }
  }
}