2 ms·
That where is not a one-off construct, it's used with switch statements: switch i { case 1...100 where i % 2 == 0: print("\(i) is a small even number
by saagarjha 6y ago
That where is not a one-off construct, it's used with switch statements:
switch i {
case 1...100 where i % 2 == 0:
print("\(i) is a small even number")
case ..<0:
print("\(i) is negative")
default:
print("I couldn't care less")
}
Or generic constraints:
struct Vector<T> where T: Numeric {
// ...
}
If you so wish, you can always use any of the functional constructs as well, as in
for i in (0..<10).filter { $0 % 2 == 0 } {
print(i)
}
- kbenson 6y agoSo it looks like it's a general modifier to a range type, so can be used where those work. That's slightly better, but if filter exists, why not just use that? One of the biggest criticisms that Perl gets is that there's so many different ways to do things, and that's somewhat deserved, so the question is what does "where" offer that "filter" doesn't other than another keyword and concept you have to learn to understand the language? What's the point if it's not really that much more expressive or clear? > struct Vector<T> where T: Numeric Is this really the same thing? This seems like a case where the same word is used to mean something else, even if they are loosely conceptually the same.
- jiofih 6y agoBetter learn a new, generic concept than obscure syntax I’ll see combined 1000 different ways on the same codebase.
- solidsnack9000 6y agoIt isn't actually a modifier to a range type -- it modifies other constructs, like looping or conditionals. The examples don't show it but literally any condition can go in the where clause, even something like `where random() % 7 == 2`.