openlang

Swift - Making integers positive

can an integer be converted to its absolute value?

for instance

  -7  
  to  
   7

I tried UInt() already, thinking it would turn the Int into an unsigned value, but that attempt didn't work.

The conversation continues 4

Follow the reasoning
  1. Permalink

    Using the usual abs() function handles this nicely:

      let sample = -7
      print(abs(sample))
      // 7
  2. Permalink

    In Swift 5, either of the following two approaches lets you turn an integer into its absolute value.

    #1. Obtain an Int's absolute value through its magnitude property

    The Int type provides magnitude (https://developer.apple.com/documentation/swift/int/2886869-magnitude). This property is declared like this:

      var magnitude: UInt { get }

    For a numeric input x, the value x.magnitude gives x's absolute value.

    Here is an example using the magnitude property to retrieve the absolute value from an instance of Int:

      let input = -4
      print(input.magnitude) // prints: 4

    #2. Obtain an Int's absolute value through the abs(_:) method

    A global numeric function in Swift is named abs(_:) (https://developer.apple.com/documentation/swift/2885649-abs). Its method declaration is:

      func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric

    Gives the supplied number's absolute value.

    Here is an example calling the global abs(_:) function to retrieve the absolute value from an instance of Int:

      let input = -4
      print(abs(input)) // prints: 4
  3. Permalink

    For the absolute value of either a double or an Int, call the fabs function:

      var sample = -14.28
      print(fabs(sample)) // 14.28
      sample = -9
      print(fabs(sample)) // 9
  4. Permalink

    To make a number positive or leave it positive.

    You can do this:

      abs() for int
      fabs() for double
      fabsf() for float

Other sides of the same question

  1. Ported a short MATLAB script to R and one result came back as a matrix

    Hi all. I'm porting a short MATLAB script from a colleague (Priyesh, 2023) into R, because the rest of our pipeline is R and…

    Replies 2Latest activity rmatlab
  2. Freezer with zero readings reports status "ok", what am I missing

    My nightly audit script (Rscript, base R) flags freezers whose peak temp is above a limit. Last night U-03's logger was unplu…

    Replies 2Latest activity r
  3. A loop that allocated a column at a time

    Slicing in Julia copies, which I knew and then forgot inside a loop. Take a function that walks the columns of a matrix and d…

    Replies 2Latest activity julia