Related
I am trying to use recursion in Swift to print out the Fibonacci sequence for a number "n" iterations. However, I keep getting the same error.
I have already tried doing it without recursion and was able to do it. However, I am now trying to do in a more complex and "computer scientisty" way by using recursion.
func fibonacciSequence (n: Int) -> [Int] {
// Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.
var fibonacciArray = [Int]()
for n in 0 ... n {
if n == 0 {
fibonacciArray.append(0)
}
else if n == 1 {
fibonacciArray.append(1)
}
else {
fibonacciArray.append (fibonacciSequence(n: (n - 1)) +
fibonacciSequence(n: (n-2)))
}
}
return fibonacciArray
I expect to call the function with a number n and for the function to print out the Fibonacci sequence. Example: if n = 5, I expect the console to print 0, 1, 1, 2, 3, 5. The error I get is this: (Cannot convert value of type '[Int]' to expected argument type 'Int').
As pointed out above, the return value is causing an error when summed. A possible way (but not recursive) of fixing the code would be to simply change the else statement:
func fibonacciSequence (n: Int) -> [Int] {
// Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.
var fibonacciArray = [Int]()
for n in 0 ... n {
if n == 0 {
fibonacciArray.append(0)
}
else if n == 1 {
fibonacciArray.append(1)
}
else {
fibonacciArray.append (fibonacciArray[n-1] + fibonacciArray[n-2] )
}
}
return fibonacciArray
}
A recursive solution would be the following:
func fibonacciSequence (n: Int, sumOne: Int, sumTwo: Int, counter: Int, start: Bool) {
if start {
print(0)
print(1)
}
if counter == -1 {
print(1)
}
if (counter == n - 2) {
return
}
let sum = sumOne + sumTwo
print(sum)
fibonacciSequence(n: n, sumOne: sumTwo , sumTwo: sum, counter: counter + 1, start: false)
}
fibonacciSequence(n: 8, sumOne: 0, sumTwo: 1, counter: 0, start: true)
There is probably a "nicer" way, but I hope it helps. Cheers.
These is my solution for fabonacci series in swift 5 playground
func fibonacci(n: Int) {
var num1 = 0
var num2 = 1
var nextNum = Int()
let i = 1
var array = [Int]()
array.append(num1)
array.append(num2)
for _ in i...n {
nextNum = num1 + num2
num1 = num2
num2 = nextNum
array.append(num2)
print(array)
}
print("result = \(num2)")
}
print(fibonacci(n: 5))
let fibonacci = sequence(state: (0, 1)) {(state: inout (Int, Int)) -> Int? in
defer { state = (state.1, state.0 + state.1) }
return state.0
}
//limit 10
for number in fibonacci.prefix(10) {
print(number)
}
// MARK: - Function
func fibonacciSeries(_ num1 : Int,_ num2 : Int,_ term : Int,_ termCount : Int) -> Void{
if termCount != term{
print(num1)
fibonacciSeries(num2, num2+num1, term, termCount + 1)
}
}
// MARK: - Calling Of Function fibonacciSeries(0, 1, 5, 0)
// MARK: - out Put 0 1 1 2 3
Note Need to Change only No Of term for fibonacci Series.
func fibonacci(n: Int) {
var seq: [Int] = n == 0 ? [0] : [0, 1]
var curNum = 2
while curNum < n{
seq.append(seq[curNum - 1] + seq[curNum - 2])
curNum += 1 }
print(seq) }
Recursive way of fabonacci -> Solutions
func fibo( n: Int) -> Int {
guard n > 1 else { return n }
return fibo(n: n-1) + fibo(n: n-2)
}
I want to know how many common characters in the given sets.
Input: J = "aA", S = "aAAbbbb"
Output: 3
In the python solution for this as follows:
lookup = set(J)
return sum(s in lookup for s in S)
I have following solution in Swift it works, but it looks too wordy. I want to learn shorter way of it.
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J) ;
var sy = 0;
for c in S
{
if lookup.contains(c)
{
sy += 1;
}
}
return sy;
}
}
As a small variation of Sh_Khan's answer you can use reduce to
count the number of matching elements without creating an intermediate
array:
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.reduce(0) { lookup.contains($1) ? $0 + 1 : $0 }
}
In Swift 5 there will be a count(where:) sequence method for this purpose,
see SE-0220 count(where:).
You can try
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.filter { lookup.contains($0) }.count
}
}
I am looking at Xcode 7.3 notes and I notice this issue.
The ++ and -- operators have been deprecated
Could some one explain why it is deprecated? And am I right that in new version of Xcode now you going to use instead of ++ this x += 1;
Example:
for var index = 0; index < 3; index += 1 {
print("index is \(index)")
}
A full explanation here from Chris Lattner, Swift's creator. I'll summarize the points:
It's another function you have to learn while learning Swift
Not much shorter than x += 1
Swift is not C. Shouldn't carry them over just to please C programmers
Its main use is in C-style for loop: for i = 0; i < n; i++ { ... }, which Swift has better alternatives, like for i in 0..<n { ... } (C-style for loop is going out as well)
Can be tricky to read and maintain, for eg, what's the value of x - ++x or foo(++x, x++)?
Chris Lattner doesn't like it.
For those interested (and to avoid link rot), Lattner's reasons in his own words are:
These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language.
Their expressive advantage is minimal - x++ is not much shorter than x += 1.
Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model.
Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc.
Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand.
While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined.
These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc.
Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?"
I realize that this comment doesn't answer the question nevertheless there may be people looking for a solution how to keep these operators working and such a solution can be found in the bottom. đ
I personally prefer ++ and -- operators. I can't agree with the opinion that they are tricky or hard to manage. Once the developer understand what these operators do (and we are talking about pretty simple stuff) the code should be very clear.
In the explanation why the operators were deprecated is mentioned that their main use was in C-style for loops. I don't know about others but I personally don't use C-style loops at all and there are still many other places or situations when ++ or -- operator is useful.
I would like to also mention that varName++ returns a value so it can be used in the return whereas varName += 1 can not.
For any of you who would like to keep these operators working here is the solution:
prefix operator ++ {}
postfix operator ++ {}
prefix operator -- {}
postfix operator -- {}
// Increment
prefix func ++(inout x: Int) -> Int {
x += 1
return x
}
postfix func ++(inout x: Int) -> Int {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt) -> UInt {
x += 1
return x
}
postfix func ++(inout x: UInt) -> UInt {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int8) -> Int8 {
x += 1
return x
}
postfix func ++(inout x: Int8) -> Int8 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt8) -> UInt8 {
x += 1
return x
}
postfix func ++(inout x: UInt8) -> UInt8 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int16) -> Int16 {
x += 1
return x
}
postfix func ++(inout x: Int16) -> Int16 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt16) -> UInt16 {
x += 1
return x
}
postfix func ++(inout x: UInt16) -> UInt16 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int32) -> Int32 {
x += 1
return x
}
postfix func ++(inout x: Int32) -> Int32 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt32) -> UInt32 {
x += 1
return x
}
postfix func ++(inout x: UInt32) -> UInt32 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int64) -> Int64 {
x += 1
return x
}
postfix func ++(inout x: Int64) -> Int64 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt64) -> UInt64 {
x += 1
return x
}
postfix func ++(inout x: UInt64) -> UInt64 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Double) -> Double {
x += 1
return x
}
postfix func ++(inout x: Double) -> Double {
x += 1
return (x - 1)
}
prefix func ++(inout x: Float) -> Float {
x += 1
return x
}
postfix func ++(inout x: Float) -> Float {
x += 1
return (x - 1)
}
prefix func ++(inout x: Float80) -> Float80 {
x += 1
return x
}
postfix func ++(inout x: Float80) -> Float80 {
x += 1
return (x - 1)
}
prefix func ++<T : _Incrementable>(inout i: T) -> T {
i = i.successor()
return i
}
postfix func ++<T : _Incrementable>(inout i: T) -> T {
let y = i
i = i.successor()
return y
}
// Decrement
prefix func --(inout x: Int) -> Int {
x -= 1
return x
}
postfix func --(inout x: Int) -> Int {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt) -> UInt {
x -= 1
return x
}
postfix func --(inout x: UInt) -> UInt {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int8) -> Int8 {
x -= 1
return x
}
postfix func --(inout x: Int8) -> Int8 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt8) -> UInt8 {
x -= 1
return x
}
postfix func --(inout x: UInt8) -> UInt8 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int16) -> Int16 {
x -= 1
return x
}
postfix func --(inout x: Int16) -> Int16 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt16) -> UInt16 {
x -= 1
return x
}
postfix func --(inout x: UInt16) -> UInt16 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int32) -> Int32 {
x -= 1
return x
}
postfix func --(inout x: Int32) -> Int32 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt32) -> UInt32 {
x -= 1
return x
}
postfix func --(inout x: UInt32) -> UInt32 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int64) -> Int64 {
x -= 1
return x
}
postfix func --(inout x: Int64) -> Int64 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt64) -> UInt64 {
x -= 1
return x
}
postfix func --(inout x: UInt64) -> UInt64 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Double) -> Double {
x -= 1
return x
}
postfix func --(inout x: Double) -> Double {
x -= 1
return (x + 1)
}
prefix func --(inout x: Float) -> Float {
x -= 1
return x
}
postfix func --(inout x: Float) -> Float {
x -= 1
return (x + 1)
}
prefix func --(inout x: Float80) -> Float80 {
x -= 1
return x
}
postfix func --(inout x: Float80) -> Float80 {
x -= 1
return (x + 1)
}
prefix func --<T : BidirectionalIndexType>(inout i: T) -> T {
i = i.predecessor()
return i
}
postfix func --<T : BidirectionalIndexType>(inout i: T) -> T {
let y = i
i = i.predecessor()
return y
}
Apple has removed the ++ and made it much simpler with the another old traditional way.
Instead of ++, you need to write +=.
Example:
var x = 1
//Increment
x += 1 //Means x = x + 1
Similarly for decrement operator --, you need to write -=
Example:
var x = 1
//Decrement
x -= 1 //Means x = x - 1
For for loops:
Increment Example:
Instead of
for var index = 0; index < 3; index ++ {
print("index is \(index)")
}
You can write:
//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)")
}
Decrement Example:
for var index = 3; index >= 0; --index {
print(index)
}
You can write:
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)
}
Hope this helps!
For Swift 4, you can restore the ++ and -- operators as extensions for Int and other types. Here is an example:
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
}
}
It works the same way for other types, such as UIInt, Int8, Float, Double, etc.
You can paste these extensions in a single file in your root directory, and they will be available for use inside all of your other files there. It works perfectly, if you check it out in a playground.
Chris Lattner has gone to war against ++ and --. He writes, âCode that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage âoverly trickyâ code which may be cute, but difficult to understandâŚ.While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-definedâŚthese fail the metric of âif we didnât already have these, would we add them to Swift 3?ââ
Apple wanted to keep swift a clean, clear, non-confusing and straight-to-the-point language. And so they deprecated ++ and -- keyword.
The Fix-it feature of Xcode gives clear answer to this.
Replace ++ increment operator with old-fashioned value += 1 (short-hand operator) and -- decrement operator with value -= 1
Here is a generic version of some of the code posted so far. I would voice the same concerns as others: it is a best practice to not use these in Swift. I agree that this could be confusing for those reading your code in the future.
prefix operator ++
prefix operator --
prefix func ++<T: Numeric> (_ val: inout T) -> T {
val += 1
return val
}
prefix func --<T: Numeric> (_ val: inout T) -> T {
val -= 1
return val
}
postfix operator ++
postfix operator --
postfix func ++<T: Numeric> (_ val: inout T) -> T {
defer { val += 1 }
return val
}
postfix func --<T: Numeric> (_ val: inout T) -> T {
defer { val -= 1 }
return val
}
This can also be written as an extension on the Numeric type.
From the docs:
The increment/decrement operators in Swift were added very early in
the development of Swift, as a carry-over from C. These were added
without much consideration, and haven't been thought about much since
then. This document provides a fresh look at them, and ultimately
recommends we just remove them entirely, since they are confusing and
not carrying their weight.
var value : Int = 1
func theOldElegantWay() -> Int{
return value++
}
func theNewFashionWay() -> Int{
let temp = value
value += 1
return temp
}
This is definitely a downside, right?
Since you never really work with pointers in Swift, it kinda makes sense to remove the ++ and -- operators in my opinion. However if you can't live without, you may add these Swift 5+ operator declarations to your project:
#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
}
In a language without semicolons, it can be ambiguous. Is it a prefix or postfix operator?
Consider:
var x = y
++x
A human reads ++x but a parser could read this as y++.
In Swift 4.1 it could be achieved this way:
prefix operator ++
postfix operator ++
extension Int{
static prefix func ++(x: inout Int)->Int{
x += 1
return x
}
static postfix func ++(x: inout Int)->Int{
x += 1
return x-1
}
}
//example:
var t = 5
var s = t++
print("\(t) \(s)")
Notice that despite the fact that this solution in similar to previous solutions in this post, they don't work anymore in Swift 4.1 and this example does.
Also notice that whomever above mentions that += is a replacement for ++ just don't fully understand the operator as ++ combined with assignment is actually two operations, hence a shortcut.
In my example: var s = t++ does two things: assign the value of t to s and then increment t. If the ++ comes before, it's the same two operations done in reversed order.
To my opinion, the reasoning of Apple about why to remove this operator(mentioned in previous answers), is not only false reasoning but furthermore I believe it is a lie and the true reason is that they couldn't make their compiler handle it. It gave them troubles in previous versions so they gave up.
The logic of "too complicated to understand operator, hence removed" is obviously a lie because Swift contains operators far more complicated and much less useful which were not removed. Also, the vast majority of programming languages has it.
JavaScript, C, C#, Java, C++ and so many more. Programmers happily use it.
Whomever it is too difficult to understand this operator for, they and only they should do the += (or perhaps s = s + 1 if += is too complexed as well).
The strategy behind Swift is simple: Apple believes the programmer is dumb and therefore should be treated accordingly.
The truth is that Swift, launched at September 2014 was supposed to be somewhere else by now. Other languages grew up much faster.
I can list many major mistakes in the language, from serious ones: such as arrays pasted by value and not by reference, to annoying ones: variadic parameters functions can't accept an array which is the whole idea behind it.
I don't think that Apple's employees are even allowed to look at other languages such as Java so they don't even know that Apple is light years behind. Apple could have adopted Java as a language but these days, challenge is not technology, but ego is.
If they would have opened IntelliJ to write some Java, they would for sure close their business understanding that at this point, they can't and won't catch up ever.
I am looking at Xcode 7.3 notes and I notice this issue.
The ++ and -- operators have been deprecated
Could some one explain why it is deprecated? And am I right that in new version of Xcode now you going to use instead of ++ this x += 1;
Example:
for var index = 0; index < 3; index += 1 {
print("index is \(index)")
}
A full explanation here from Chris Lattner, Swift's creator. I'll summarize the points:
It's another function you have to learn while learning Swift
Not much shorter than x += 1
Swift is not C. Shouldn't carry them over just to please C programmers
Its main use is in C-style for loop: for i = 0; i < n; i++ { ... }, which Swift has better alternatives, like for i in 0..<n { ... } (C-style for loop is going out as well)
Can be tricky to read and maintain, for eg, what's the value of x - ++x or foo(++x, x++)?
Chris Lattner doesn't like it.
For those interested (and to avoid link rot), Lattner's reasons in his own words are:
These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language.
Their expressive advantage is minimal - x++ is not much shorter than x += 1.
Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model.
Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc.
Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand.
While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined.
These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc.
Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?"
I realize that this comment doesn't answer the question nevertheless there may be people looking for a solution how to keep these operators working and such a solution can be found in the bottom. đ
I personally prefer ++ and -- operators. I can't agree with the opinion that they are tricky or hard to manage. Once the developer understand what these operators do (and we are talking about pretty simple stuff) the code should be very clear.
In the explanation why the operators were deprecated is mentioned that their main use was in C-style for loops. I don't know about others but I personally don't use C-style loops at all and there are still many other places or situations when ++ or -- operator is useful.
I would like to also mention that varName++ returns a value so it can be used in the return whereas varName += 1 can not.
For any of you who would like to keep these operators working here is the solution:
prefix operator ++ {}
postfix operator ++ {}
prefix operator -- {}
postfix operator -- {}
// Increment
prefix func ++(inout x: Int) -> Int {
x += 1
return x
}
postfix func ++(inout x: Int) -> Int {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt) -> UInt {
x += 1
return x
}
postfix func ++(inout x: UInt) -> UInt {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int8) -> Int8 {
x += 1
return x
}
postfix func ++(inout x: Int8) -> Int8 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt8) -> UInt8 {
x += 1
return x
}
postfix func ++(inout x: UInt8) -> UInt8 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int16) -> Int16 {
x += 1
return x
}
postfix func ++(inout x: Int16) -> Int16 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt16) -> UInt16 {
x += 1
return x
}
postfix func ++(inout x: UInt16) -> UInt16 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int32) -> Int32 {
x += 1
return x
}
postfix func ++(inout x: Int32) -> Int32 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt32) -> UInt32 {
x += 1
return x
}
postfix func ++(inout x: UInt32) -> UInt32 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Int64) -> Int64 {
x += 1
return x
}
postfix func ++(inout x: Int64) -> Int64 {
x += 1
return (x - 1)
}
prefix func ++(inout x: UInt64) -> UInt64 {
x += 1
return x
}
postfix func ++(inout x: UInt64) -> UInt64 {
x += 1
return (x - 1)
}
prefix func ++(inout x: Double) -> Double {
x += 1
return x
}
postfix func ++(inout x: Double) -> Double {
x += 1
return (x - 1)
}
prefix func ++(inout x: Float) -> Float {
x += 1
return x
}
postfix func ++(inout x: Float) -> Float {
x += 1
return (x - 1)
}
prefix func ++(inout x: Float80) -> Float80 {
x += 1
return x
}
postfix func ++(inout x: Float80) -> Float80 {
x += 1
return (x - 1)
}
prefix func ++<T : _Incrementable>(inout i: T) -> T {
i = i.successor()
return i
}
postfix func ++<T : _Incrementable>(inout i: T) -> T {
let y = i
i = i.successor()
return y
}
// Decrement
prefix func --(inout x: Int) -> Int {
x -= 1
return x
}
postfix func --(inout x: Int) -> Int {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt) -> UInt {
x -= 1
return x
}
postfix func --(inout x: UInt) -> UInt {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int8) -> Int8 {
x -= 1
return x
}
postfix func --(inout x: Int8) -> Int8 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt8) -> UInt8 {
x -= 1
return x
}
postfix func --(inout x: UInt8) -> UInt8 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int16) -> Int16 {
x -= 1
return x
}
postfix func --(inout x: Int16) -> Int16 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt16) -> UInt16 {
x -= 1
return x
}
postfix func --(inout x: UInt16) -> UInt16 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int32) -> Int32 {
x -= 1
return x
}
postfix func --(inout x: Int32) -> Int32 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt32) -> UInt32 {
x -= 1
return x
}
postfix func --(inout x: UInt32) -> UInt32 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Int64) -> Int64 {
x -= 1
return x
}
postfix func --(inout x: Int64) -> Int64 {
x -= 1
return (x + 1)
}
prefix func --(inout x: UInt64) -> UInt64 {
x -= 1
return x
}
postfix func --(inout x: UInt64) -> UInt64 {
x -= 1
return (x + 1)
}
prefix func --(inout x: Double) -> Double {
x -= 1
return x
}
postfix func --(inout x: Double) -> Double {
x -= 1
return (x + 1)
}
prefix func --(inout x: Float) -> Float {
x -= 1
return x
}
postfix func --(inout x: Float) -> Float {
x -= 1
return (x + 1)
}
prefix func --(inout x: Float80) -> Float80 {
x -= 1
return x
}
postfix func --(inout x: Float80) -> Float80 {
x -= 1
return (x + 1)
}
prefix func --<T : BidirectionalIndexType>(inout i: T) -> T {
i = i.predecessor()
return i
}
postfix func --<T : BidirectionalIndexType>(inout i: T) -> T {
let y = i
i = i.predecessor()
return y
}
Apple has removed the ++ and made it much simpler with the another old traditional way.
Instead of ++, you need to write +=.
Example:
var x = 1
//Increment
x += 1 //Means x = x + 1
Similarly for decrement operator --, you need to write -=
Example:
var x = 1
//Decrement
x -= 1 //Means x = x - 1
For for loops:
Increment Example:
Instead of
for var index = 0; index < 3; index ++ {
print("index is \(index)")
}
You can write:
//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)")
}
Decrement Example:
for var index = 3; index >= 0; --index {
print(index)
}
You can write:
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)
}
Hope this helps!
For Swift 4, you can restore the ++ and -- operators as extensions for Int and other types. Here is an example:
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
}
}
It works the same way for other types, such as UIInt, Int8, Float, Double, etc.
You can paste these extensions in a single file in your root directory, and they will be available for use inside all of your other files there. It works perfectly, if you check it out in a playground.
Chris Lattner has gone to war against ++ and --. He writes, âCode that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage âoverly trickyâ code which may be cute, but difficult to understandâŚ.While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-definedâŚthese fail the metric of âif we didnât already have these, would we add them to Swift 3?ââ
Apple wanted to keep swift a clean, clear, non-confusing and straight-to-the-point language. And so they deprecated ++ and -- keyword.
The Fix-it feature of Xcode gives clear answer to this.
Replace ++ increment operator with old-fashioned value += 1 (short-hand operator) and -- decrement operator with value -= 1
Here is a generic version of some of the code posted so far. I would voice the same concerns as others: it is a best practice to not use these in Swift. I agree that this could be confusing for those reading your code in the future.
prefix operator ++
prefix operator --
prefix func ++<T: Numeric> (_ val: inout T) -> T {
val += 1
return val
}
prefix func --<T: Numeric> (_ val: inout T) -> T {
val -= 1
return val
}
postfix operator ++
postfix operator --
postfix func ++<T: Numeric> (_ val: inout T) -> T {
defer { val += 1 }
return val
}
postfix func --<T: Numeric> (_ val: inout T) -> T {
defer { val -= 1 }
return val
}
This can also be written as an extension on the Numeric type.
From the docs:
The increment/decrement operators in Swift were added very early in
the development of Swift, as a carry-over from C. These were added
without much consideration, and haven't been thought about much since
then. This document provides a fresh look at them, and ultimately
recommends we just remove them entirely, since they are confusing and
not carrying their weight.
var value : Int = 1
func theOldElegantWay() -> Int{
return value++
}
func theNewFashionWay() -> Int{
let temp = value
value += 1
return temp
}
This is definitely a downside, right?
Since you never really work with pointers in Swift, it kinda makes sense to remove the ++ and -- operators in my opinion. However if you can't live without, you may add these Swift 5+ operator declarations to your project:
#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
}
In a language without semicolons, it can be ambiguous. Is it a prefix or postfix operator?
Consider:
var x = y
++x
A human reads ++x but a parser could read this as y++.
In Swift 4.1 it could be achieved this way:
prefix operator ++
postfix operator ++
extension Int{
static prefix func ++(x: inout Int)->Int{
x += 1
return x
}
static postfix func ++(x: inout Int)->Int{
x += 1
return x-1
}
}
//example:
var t = 5
var s = t++
print("\(t) \(s)")
Notice that despite the fact that this solution in similar to previous solutions in this post, they don't work anymore in Swift 4.1 and this example does.
Also notice that whomever above mentions that += is a replacement for ++ just don't fully understand the operator as ++ combined with assignment is actually two operations, hence a shortcut.
In my example: var s = t++ does two things: assign the value of t to s and then increment t. If the ++ comes before, it's the same two operations done in reversed order.
To my opinion, the reasoning of Apple about why to remove this operator(mentioned in previous answers), is not only false reasoning but furthermore I believe it is a lie and the true reason is that they couldn't make their compiler handle it. It gave them troubles in previous versions so they gave up.
The logic of "too complicated to understand operator, hence removed" is obviously a lie because Swift contains operators far more complicated and much less useful which were not removed. Also, the vast majority of programming languages has it.
JavaScript, C, C#, Java, C++ and so many more. Programmers happily use it.
Whomever it is too difficult to understand this operator for, they and only they should do the += (or perhaps s = s + 1 if += is too complexed as well).
The strategy behind Swift is simple: Apple believes the programmer is dumb and therefore should be treated accordingly.
The truth is that Swift, launched at September 2014 was supposed to be somewhere else by now. Other languages grew up much faster.
I can list many major mistakes in the language, from serious ones: such as arrays pasted by value and not by reference, to annoying ones: variadic parameters functions can't accept an array which is the whole idea behind it.
I don't think that Apple's employees are even allowed to look at other languages such as Java so they don't even know that Apple is light years behind. Apple could have adopted Java as a language but these days, challenge is not technology, but ego is.
If they would have opened IntelliJ to write some Java, they would for sure close their business understanding that at this point, they can't and won't catch up ever.
I created this infix operator ^^ as a substitute to using the pow function:
infix operator ^^ { associativity left precedence 155 }
func ^^ <T: IntegerLiteralConvertible>(left: T, right: T) -> T {
return pow(left as Double, right as Double)
}
I used the IntegerLiteralConvertible protocol as a type constraint for the generics left and right, because from my understanding this diagramm shows, that it basically includes all number types.
In order to use the pow function I have to downcast left and right to Double though, which I did using the as operator. It's not the safest approach, but that's besides the point.
When implementing the function this way swift tells me:
<stdin>:4:12: error: cannot invoke 'pow' with an argument list of type '(Double, Double)'
return pow(left as Double, right as Double)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now as far as I know pow takes two Doubles as parameters, so why is it complaining about this?
why is it complaining about this?
Because pow returns Double. And Double is not identical to T. The error message is misleading, but it means "Cannot find pow that accepts (Double, Double) and returns T type"
I think you are misunderstanding "cast" in Swift. In Swift as does not convert numeric types.
let intVal:Int = 12
let doubleVal:Double = intVal as Double
// ^ [!] error: 'Int' is not convertible to 'Double'
And If the type of operand is not predictable at compile time, invalid casting causes runtime error:
func foo<T: IntegerLiteralConvertible>(x: T) {
x as Double // <-- Execution was interrupted
}
foo(12 as Int)
Instead, we must explicitly "convert" them. see the document: Numeric Type Conversion
let intVal:Int = 12
let doubleVal:Double = Double(intVal)
This works only because Double has init(_ v: Int) initializer. The following code does not compile:
func foo<T: IntegerLiteralConvertible>(x: T) {
Double(x)
// ^~~~~~~~~ [!] error: cannot invoke 'init' with an argument of type 'T'
}
Because Double does not have init<T:IntegerLiteralConvertible>(_ val:T) initializer.
So, if you want to use pow(), you must convert T to Double for arguments, and convert Double to T for returning value. And there is no simple solution for that.
Thanks #Martin R. This comes from the only question I have posted so far at S.O.
import Cocoa
Protocols
protocol Fraction { init(_ value:Double) ; var asDouble : Double { get } }
protocol Text { init(_ value:String) ; var asString : String { get } }
Extensions
extension String : Text { var asString : String { return self } }
extension Double : Fraction { var asDouble : Double { return self } }
extension Float : Fraction { var asDouble : Double { return Double(self) } }
extension CGFloat : Fraction { var asDouble : Double { return Double(self) } }
infix operator ^^
infix operator ^^ { associativity left precedence 170 }
func ^^<T:IntegerType, U:IntegerType> (var base:T, var power:U) -> T {
if power < 0 { return 0 }
var result: T = 1
if power > 0 {
if power % 2 == 1 { result *= base }
power /= 2
}
while power > 0 {
base *= base
if power % 2 == 1 { result *= base }
power /= 2
}
return result
}
func ^^<T:Fraction, U:Fraction> (base: T, power: U) -> T {
return T(pow(base.asDouble, power.asDouble))
}
func ^^<T:Text, U:IntegerType> (base:T, var power:U) -> T {
if power <= 0 { return "" as T }
if power == 1 { return base as T }
return power > 1 ? {var result = ""; for x in 1...power { result+=base.asString };return result as T}() : "" as T
}
func ^^<T:Text, U:Text> (base:T, var power:U) -> T {
return "" as T
}
testing
println(1 ^^ -1) // "0" Int
println(1 ^^ 0) // "1" Int
println(1 ^^ 1) // "1" Int
println(1 ^^ 2) // "1" Int
println(2 ^^ -1) // "0" Int
println(2 ^^ 0) // "1" Int
println(2 ^^ 1) // "2" Int
println(2 ^^ 2) // "4" Int
println(2 ^^ 8) // "256" Int
println(2 ^^ 16) // "65536" Int
println(2 ^^ 32) // "4294967296" Int
println(2 ^^ 62) // "4611686018427387904"
println(UInt(2) ^^ 8) // "256" UInt
println(UInt64(2) ^^ 8) // "256" UInt64