Set a Variable to the < ("Less Than") Operator as a Function in Swift

Set a variable to the ( less than ) operator as a function in Swift?

If you give comparator an explicit type, then it will work.

var comparator: (Int, Int) -> Bool = (<)

or

var comparator: (Double, Double) -> Bool = (<)

Less than < isn't a single function, but a whole collection of them for different types. By identifying the type you are interested in comparing, you allow the compiler to select the correct less than function.

Setting a variable to an operator function

Surrounding the operator with parentheses, and specifying the type explicitly, allows it to parse and typecheck:

let op: (Int, Int) -> Int = (+)

Lesser than or greater than in Swift switch statement

Here's one approach. Assuming someVar is an Int or other Comparable, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where keyword:

var someVar = 3

switch someVar {
case let x where x < 0:
print("x is \(x)")
case let x where x == 0:
print("x is \(x)")
case let x where x > 0:
print("x is \(x)")
default:
print("this is impossible")
}

This can be simplified a bit:

switch someVar {
case _ where someVar < 0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
case _ where someVar > 0:
print("someVar is \(someVar)")
default:
print("this is impossible")
}

You can also avoid the where keyword entirely with range matching:

switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}

Can I use a function stored in a variable as operator in Swift?

The best I can come up with is something like:

infix operator <-> {} // define the operator <->

func <-> (lhs:Int, rhs:Int) -> Int {
return arrowFunction(lhs, rhs)
}

let arrowFunction : (Int, Int) -> Int = (+)

println("\(2 <-> 7)")

Mathematical sign as function parameter

In swift signs are functions name for a specified mathematic operation. To pass sign as parameter the parameter type must be function that takes two numbers and return a number. If you command + click on any sign you will see its definition as follow :

public func +(lhs: UInt8, rhs: UInt8) -> UInt8

public func +(lhs: Int8, rhs: Int8) -> Int8

public func +(lhs: UInt16, rhs: UInt16) -> UInt16

public func +(lhs: Int16, rhs: Int16) -> Int16

public func +(lhs: UInt32, rhs: UInt32) -> UInt32

public func +(lhs: Int32, rhs: Int32) -> Int32

public func +(lhs: UInt64, rhs: UInt64) -> UInt64

public func +(lhs: Int64, rhs: Int64) -> Int64

public func +(lhs: UInt, rhs: UInt) -> UInt

public func +(lhs: Int, rhs: Int) -> Int

In your case your reduce function should look as the following one

func reduce(sign: (Int,Int)->Int) -> Int{

return sign(2,3)
}

reduce(*)
reduce(-)

How do I check if an integer is even or odd?

Use the modulo (%) operator to check if there's a remainder when dividing by 2:

if (x % 2) { /* x is odd */ }

A few people have criticized my answer above stating that using x & 1 is "faster" or "more efficient". I do not believe this to be the case.

Out of curiosity, I created two trivial test case programs:

/* modulo.c */
#include <stdio.h>

int main(void)
{
int x;
for (x = 0; x < 10; x++)
if (x % 2)
printf("%d is odd\n", x);
return 0;
}

/* and.c */
#include <stdio.h>

int main(void)
{
int x;
for (x = 0; x < 10; x++)
if (x & 1)
printf("%d is odd\n", x);
return 0;
}

I then compiled these with gcc 4.1.3 on one of my machines 5 different times:

  • With no optimization flags.
  • With -O
  • With -Os
  • With -O2
  • With -O3

I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment.

If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know.

Finally, the modulo version is guaranteed by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

It's commonly referred to as 'shorthand' or the Ternary Operator.

$test = isset($_GET['something']) ? $_GET['something'] : '';

means

if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}

To break it down:

$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)

Or...

// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)

Does Typescript support the ?. operator? (And, what's it called?)

Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:

At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses.

Refer to the TypeScript 3.7 release notes for more details.


Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).

As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:

  • CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):

The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined.

  • C# calls this a null-conditional operator.

a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.

  • Kotlin refers to it as the safe call operator.

There are probably lots of other examples, too.

Printing a variable memory address in swift

Swift 2

This is now part of the standard library: unsafeAddressOf.

/// Return an UnsafePointer to the storage used for `object`.  There's
/// not much you can do with this other than use it to identify the
/// object

Swift 3

For Swift 3, use withUnsafePointer:

var str = "A String"
withUnsafePointer(to: &str) {
print(" str value \(str) has address: \($0)")
}

How to enumerate an enum with String type?

Swift 4.2+

Starting with Swift 4.2 (with Xcode 10), just add protocol conformance to CaseIterable to benefit from allCases. To add this protocol conformance, you simply need to write somewhere:

extension Suit: CaseIterable {}

If the enum is your own, you may specify the conformance directly in the declaration:

enum Suit: String, CaseIterable { case spades = "♠"; case hearts = "♥"; case diamonds = "♦"; case clubs = "♣" }

Then the following code will print all possible values:

Suit.allCases.forEach {
print($0.rawValue)
}


Compatibility with earlier Swift versions (3.x and 4.x)

If you need to support Swift 3.x or 4.0, you may mimic the Swift 4.2 implementation by adding the following code:

#if !swift(>=4.2)
public protocol CaseIterable {
associatedtype AllCases: Collection where AllCases.Element == Self
static var allCases: AllCases { get }
}
extension CaseIterable where Self: Hashable {
static var allCases: [Self] {
return [Self](AnySequence { () -> AnyIterator<Self> in
var raw = 0
var first: Self?
return AnyIterator {
let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) }
if raw == 0 {
first = current
} else if current == first {
return nil
}
raw += 1
return current
}
})
}
}
#endif


Related Topics



Leave a reply



Submit