Hacker News new | ask | show | jobs
by zapzupnz 2751 days ago
Swift has it. I'm sure a few languages must have it.

    if (2...4).contains(x)
2 comments

This doesn't work for me:

  $ swift
  Welcome to Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1). Type :help for assistance.
    1> let x = 3
  x: Int = 3
    2> if x in 2...4 {}
  error: repl.swift:2:6: error: expected '{' after 'if' condition
  if x in 2...4 {}
       ^
Are you sure you didn't mean to use if case?

  if case 2...4 = x
Yeah, I was wrong. I updated my comment. I think I just meant to check if a range contains a value, as I changed it to.
You can use ~= if you're looking for a succinct way to do an operation like this:

  if 2...4 ~= x
I didn't know about this. Brilliant, cheers!
Does that work for floats?
Yes, if you use the pattern matching operator I suggested to the original comment's author:

  $ swift
  Welcome to Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1). Type :help for assistance.
    1> let x = 3
  x: Int = 3
    2> let y = 3.0
  y: Double = 3
    3> 2...4 ~= x
  $R0: Bool = true
    4> 2...4 ~= y
  $R1: Bool = true
Floats that aren’t equivalent to ints: 2.5.

In some languages, similar constructs test membership in a list/range, rather than an inequality.