PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] how to extend Double and Int in Swift with the same function

 October 17, 2022     double, generics, integer, swift     No comments   

Issue

I want to create an extension for Swift Double, Int, and other numeric types that support the random(in:) function, like so:

extension Double {
    // function to generate multiple random numbers of type
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] {
        var values = [Self]()
        if count > 0 {
            for _ in 0..<count {
                values.append(Self.random(in: range))
            }
        }
        return values
    }
}

How do I do this without creating a separate extension for each type?


Solution

You can't really since there is no common protocol involved here but as far as I understand the types that has the method random(in:) can be grouped into types conforming to two protocols so you need only two implementations

// Double & Float
extension BinaryFloatingPoint {
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] where Self.RawSignificand: FixedWidthInteger {
       var values = [Self]()
       if count > 0 {
           for _ in 0..<count {
               values.append(Self.random(in: range))
           }
       }
       return values
   }
}

// Int & UInt
extension FixedWidthInteger {
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] {
       var values = [Self]()
       if count > 0 {
           for _ in 0..<count {
               values.append(Self.random(in: range))
           }
       }
       return values
   }
}


Answered By - Joakim Danielson
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing