Xcode 7.3 のメモを見ていると、この問題に気づきました。
++ および -- 演算子は廃止されました
廃止された理由を誰かが説明できますか? そして、Xcode の新しいバージョンでは、これの代わりに使用するようになり++
ましたx += 1
。
例:
for var index = 0; index < 3; index += 1 {
print("index is \(index)")
}
Apple は を削除++
し、別の古い伝統的な方法でよりシンプルにしました。
の代わりに++
、書く必要があります+=
。
例:
var x = 1
//Increment
x += 1 //Means x = x + 1
同様に、デクリメント演算子--
については、次のように書く必要があります-=
例:
var x = 1
//Decrement
x -= 1 //Means x = x - 1
for
ループの場合:
増分の例:
それ以外の
for var index = 0; index < 3; index ++ {
print("index is \(index)")
}
あなたは書ける:
//Example 1
for index in 0..<3 {
print("index is \(index)")
}
//Example 2
for index in 0..<someArray.count {
print("index is \(index)")
}
//Example 3
for index in 0...(someArray.count - 1) {
print("index is \(index)")
}
デクリメントの例:
for var index = 3; index >= 0; --index {
print(index)
}
あなたは書ける:
for index in 3.stride(to: 1, by: -1) {
print(index)
}
//prints 3, 2
for index in 3.stride(through: 1, by: -1) {
print(index)
}
//prints 3, 2, 1
for index in (0 ..< 3).reverse() {
print(index)
}
for index in (0 ... 3).reverse() {
print(index)
}
お役に立てれば!
++
Swift 4 では、 and--
演算子を and の拡張機能として復元できInt
ます。次に例を示します。
extension Int {
@discardableResult
static prefix func ++(x: inout Int) -> Int {
x += 1
return x
}
static postfix func ++(x: inout Int) -> Int {
defer {x += 1}
return x
}
@discardableResult
static prefix func --(x: inout Int) -> Int {
x -= 1
return x
}
static postfix func --(x: inout Int) -> Int {
defer {x -= 1}
return x
}
}
UIInt
、Int8
、Float
、などの他のタイプでも同じように機能しますDouble
。
これらの拡張機能をルート ディレクトリの 1 つのファイルに貼り付けると、そこにある他のすべてのファイル内で使用できるようになります。遊び場でチェックアウトすると、完全に機能します。
var value : Int = 1
func theOldElegantWay() -> Int{
return value++
}
func theNewFashionWay() -> Int{
let temp = value
value += 1
return temp
}
これは間違いなくマイナス面ですよね?
Swift ではポインターを実際に操作することはないので、私の意見では++
and演算子を削除するのは理にかなっています。--
ただし、これなしでは生きられない場合は、これらのSwift 5+演算子宣言をプロジェクトに追加できます。
@discardableResult
public prefix func ++<T: Numeric>(i: inout T) -> T {
i += 1
return i
}
@discardableResult
public postfix func ++<T: Numeric>(i: inout T) -> T {
defer { i += 1 }
return i
}
@discardableResult
public prefix func --<T: Numeric>(i: inout T) -> T {
i -= 1
return i
}
@discardableResult
public postfix func --<T: Numeric>(i: inout T) -> T {
defer { i -= 1 }
return i
}