Swift 一元运算符'++';

Swift 一元运算符'++';,swift,operator-keyword,Swift,Operator Keyword,我对Swift感兴趣并开始学习,但我无法解决这个问题: func countvalue(tableau : [String]){ var b : Int = 0 for var b in tableau { b++ // Unary operator '++' cannot be applied to an operand of type @lvalue String' } print("Il y a \(b) valeurs dans ce t

我对Swift感兴趣并开始学习,但我无法解决这个问题:

func countvalue(tableau : [String]){
    var b : Int = 0

    for var b in tableau {
       b++ // Unary operator '++' cannot be applied to an operand of type @lvalue String'
    }

    print("Il y a \(b) valeurs dans ce tableau.")
}

循环中的
b
变量与循环外的变量不同,并且正在屏蔽它。由于
tableau
是一个
String
数组,因此循环中的
b
是一个
String
,因此不能递增。

循环中的
b
是一个与循环外的变量不同的变量,并且正在屏蔽它。由于
tableau
是一个
字符串的数组,循环中的
b
是一个
字符串,因此不能递增。

我想你想要的是这个

func countvalue(tableau : [String]){
    var b : Int = 0

    for _ in tableau {
       // the values in the array are not used so just ignore them with _
       b++ // Unary operator '++' cannot be applied to an operand of type @lvalue String'
    }

    print("Il y a \(b) valeurs dans ce tableau.")
}
但是如果您执行以下操作,
b
的值将是相同的

var b = tableau.count

但这要有效得多,因为它不必迭代数组的每个值。

我想你想要的是

func countvalue(tableau : [String]){
    var b : Int = 0

    for _ in tableau {
       // the values in the array are not used so just ignore them with _
       b++ // Unary operator '++' cannot be applied to an operand of type @lvalue String'
    }

    print("Il y a \(b) valeurs dans ce tableau.")
}
但是如果您执行以下操作,
b
的值将是相同的

var b = tableau.count

但是,由于它不必迭代数组的每个值,因此效率更高。

请注意,
++
操作符在Swift 3中被删除,因此最好不要习惯使用它。:)是的,正如@matt所说的,不建议在Swift 3中使用此运算符来删除它。@matt是否应该替换它?如果不是,那么增加1的更好方法是什么?@Fogmeister Swift 3正在删除令人困惑的C风格语法(包括循环的C风格)。如果要向某个对象添加1,只需向其添加1即可。@matt hehe,这很有意义:请注意,
++
操作符在Swift 3中已被删除,因此最好不要习惯使用它。:)是的,正如@matt所说的,不建议在Swift 3中使用此运算符来删除它。@matt是否应该替换它?如果不是,那么增加1的更好方法是什么?@Fogmeister Swift 3正在删除令人困惑的C风格语法(包括循环的C风格)。如果你想给某个东西加1,就加1。@matt hehe,有道理:DIt不是“完全一样”<代码>计数
效率更高;它不一定要通过所有元素才能知道有多少元素。@matt确实如此。也许我应该说“b的值与……相同:)好的,非常感谢。我的计划是创建一个类似.count的函数。:)“我的计划是创建一个类似.count的函数”明白了,我并不是说这不是一个好的练习!很明显,你正在通过实验学习一些东西,这很好。我只是说,在现实中,你永远不会创造一个像现有的
count
一样好的<代码>计数
效率更高;它不一定要通过所有元素才能知道有多少元素。@matt确实如此。也许我应该说“b的值与……相同:)好的,非常感谢。我的计划是创建一个类似.count的函数。:)“我的计划是创建一个类似.count的函数”明白了,我并不是说这不是一个好的练习!很明显,你正在通过实验学习一些东西,这很好。我只是说,在现实中,你永远不会创建一个像现有的
count
一样好的。