Ambiguous reference to member && [duplicate] - swift

This question already has answers here:
Use logical operator as combine closure in reduce
(6 answers)
Closed 6 years ago.
If I wish to calculate if all Bools in the list are true with this snippet, why won't the types be correctly inferred?
let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)

I encountered the same bug a while ago (but then with ||). If you want to use reduce for this, the easiest solution is to write
let result = bools.reduce(true, combine: { $0 && $1 })
or
let result = bools.reduce(true) { $0 && $1 }
instead. As pointed out in the comments, you can also use
let result = !bools.contains(false)
Not only is this more readable, but it's also more efficient because it will stop at the first encounter of false rather than iterating over the entire array (though the compiler might optimize this).

Related

Swift Higher order functions [duplicate]

This question already has answers here:
Beginner Swift 3: How to find pairs in array that add up to given number
(4 answers)
Closed 4 months ago.
I have the following problem,
I want to get the pair of given sum by using higher order functions. I am able to do this using iterative approach. Can someone help me to solve the problem using Swift higher order functions like map, filter etc.
let array = [1,2,3,4,5]
let givenSum = 9
for i in 0..<array.count {
let j = i + 1
for j in j..<array.count {
if array[i] + array[j] == givenSum {
print("Pair : \(array[i]),\(array[j])")
}
}
}
The output is [4,5]
Any help is appreciated. Thank you
let array = [1,5,2,3,4]
let givenSum = 9
let resultArray = array.sorted().filter{ array.firstIndex(of: givenSum-$0) ?? -1 > array.firstIndex(of: $0)!}.map{ ($0 , givenSum - $0)}
print((resultArray))
The above code gives you the expected result with higher order functions (I did not check it for lots of cases).
#Ajay K I think we need to use for loop in any way to implement this solution
Still, you can use the following improved solution
var map = [Int: Int]()
for (i, n) in array.enumerated() {
let diff = givenSum - n
if let j = map[diff] {
print("Pair : \(array[i]),\(array[j])")
}
map[n] = i
}
Happy Coding. Open for thoughts!

Can this be more Swift3-like?

What I want to do is populate an Array (sequence) by appending in the elements of another Array (availableExercises), one by one. I want to do it one by one because the sequence has to hold a given number of items. The available exercises list is in nature finite, and I want to use its elements as many times as I want, as opposed to a multiple number of the available list total.
The current code included does exactly that and works. It is possible to just paste that in a Playground to see it at work.
My question is: Is there a better Swift3 way to achieve the same result? Although the code works, I'd like to not need the variable i. Swift3 allows for structured code like closures and I'm failing to see how I could use them better. It seems to me there would be a better structure for this which is just out of reach at the moment.
Here's the code:
import UIKit
let repTime = 20 //seconds
let restTime = 10 //seconds
let woDuration = 3 //minutes
let totalWOTime = woDuration * 60
let sessionTime = repTime + restTime
let totalSessions = totalWOTime / sessionTime
let availableExercises = ["push up","deep squat","burpee","HHSA plank"]
var sequence = [String]()
var i = 0
while sequence.count < totalSessions {
if i < availableExercises.count {
sequence.append(availableExercises[i])
i += 1
}
else { i = 0 }
}
sequence
You can overcome from i using modulo of sequence.count % availableExercises.count like this way.
var sequence = [String]()
while(sequence.count < totalSessions) {
let currentIndex = sequence.count % availableExercises.count
sequence.append(availableExercises[currentIndex])
}
print(sequence)
//["push up", "deep squat", "burpee", "HHSA plank", "push up", "deep squat"]
You can condense your logic by using map(_:) and the remainder operator %:
let sequence = (0..<totalSessions).map {
availableExercises[$0 % availableExercises.count]
}
map(_:) will iterate from 0 up to (but not including) totalSessions, and for each index, the corresponding element in availableExercises will be used in the result, with the remainder operator allowing you to 'wrap around' once you reach the end of availableExercises.
This also has the advantage of preallocating the resultant array (which map(_:) will do for you), preventing it from being needlessly re-allocated upon appending.
Personally, Nirav's solution is probably the best, but I can't help offering this solution, particularly because it demonstrates (pseudo-)infinite lazy sequences in Swift:
Array(
repeatElement(availableExercises, count: .max)
.joined()
.prefix(totalSessions))
If you just want to iterate over this, you of course don't need the Array(), you can leave the whole thing lazy. Wrapping it up in Array() just forces it to evaluate immediately ("strictly") and avoids the crazy BidirectionalSlice<FlattenBidirectionalCollection<Repeated<Array<String>>>> type.

How to sort structures by property in Swift [duplicate]

This question already has answers here:
How to sort an array of custom objects by property value in Swift
(20 answers)
Closed 7 years ago.
I am trying to sort an array of structure depending on its property.
Lets say I want to sort an array of NSViews by the x coordinate.
How can I achive this?
Its a very pretty solution for that, and its called Closure Expression Syntax.
What you need to do is:
let sortedArray = sorted(allViewsArray, { (p1: NSView, p2: NSView) -> Bool in
return p1.frame.origin.x < p2.frame.origin.x
})
This will sort the alLViewsArray from the biggest X coordinate to the smallest, and store it in sortedArary.
Note, you can simplify the syntax a little, which often helps with readability (focus is on what you’re doing rather than the syntax of the types etc):
let sortedArray = sorted(allViewsArray) {
$0.frame.origin.x < $1.frame.origin.x
}
Trailing closures can be outside the function call parens, resembling other block structures like if or while; you can skip the return if the closure expression is a single statement, and you can skip the function signature and use $0, $1 etc. for the argument names.
That last one is best used only when there are no more useful names to be had (e.g. p1 is no more descriptive than $0). If you do want to give them names, you can still skip the types:
let sortedArray = sorted(allViewsArray) { p1, p2 in
p1.frame.origin.x < p2.frame.origin.x
}
Swift is sometimes a little fragile when applying this syntax sugar so occasionally you’ll find it can’t be shortened quite as much as it ought, but it usually works.

How do I sort a list of Doubles in Scala? [duplicate]

This question already has answers here:
How do I sort an array in Scala?
(7 answers)
Closed 8 years ago.
How do I sort a simple list of Doubles in Scala?
var dubs = List(1.3,4.5,2.3,3.2)
I think my question may not have accurately reflected my specific problem, since I realize now that dubs.sorted will work just fine for the above. My problem is as follows, I have a string of doubles "2.3 32.4 54.2 1.33" that I'm parsing and adding to a list
var numsAsStrings = l.split("\\s");
var x = List(Double);
var i = 0;
for( i <- 0 until numsAsStrings.length) {
x :+ numsAsStrings(i).toDouble;
}
So, I would think that I could just call x.sorted on the above, but that doesn't work... I've been looking over the sortBy, sorted, and sortWith documentation and various posts, but I thought the solution should be simpler. I think I'm missing something basic, regardless.
Use the sorted method
dubs.sorted // List(1.3, 2.3, 3.2, 4.5)

Is there an easier way to get the lesser of two values in Swift [duplicate]

This question already has answers here:
Swift equivalent for MIN and MAX macros
(5 answers)
Closed 8 years ago.
I'd like to assign the lesser of two values to a variable. In Ruby I would do something like:
my_var = [value_one, value_two].min
In Swift, of course, I can do this:
var myVar = 0.0
if valueOne < valueTwo {
myVar = valueOne
} else {
myVar = valueTwo
}
But, I'm wondering if there is a cleaner, more succinct solution.
var myVar = min(valueOne, valueTwo)
min is a standard library function that takes the lesser of two (or least of several — it's variadic) Comparable values.