0

Often I have to use floating point numbers with integers. For example:

var percent:Float = 0.6347
var wholeValue:Int = 10

var result = Int(Float(wholeValue) * percent)

I have to convert the integer wholeValue to a Float, apply the operation, then convert the results back to Int. This is really clunky and tedious. Is there a better way to operate on Ints with Floats?

Jeshua Lacock
  • 5,730
  • 1
  • 28
  • 58

2 Answers2

0

You can use generics and create template functions that accept any type. You can then create a case for each accepted parameter using typeof:

see the swift language guide link for more details and implementation. Youll want to scroll to generic functions but read the entire page/section.

https://docs.swift.org/swift-book/LanguageGuide/Generics.html

Revanth Matha
  • 69
  • 1
  • 5
0

One way to solve this is to implement your own custom operators, here is a simple example where I have created an operator ** that is used to multiply and Int and a Double and return an Int

infix operator **: MultiplicationPrecedence

extension Int {
    static func ** (left: Int, right: Double) -> Int {
        Int(Double(left) * right)
    }

    static func ** (left: Double, right: Int) -> Int {
        Int(Double(right) * left)
    }
}

Example

let x = 4 + 10 ** 4.5 - 3.4 ** 2 // x = 43

For more info see the Operator chapter in The Swift Programming Language

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52