How can I test an input condition after translating the source code using Coco/R? - swift

I have a function that I want to test in Swift. It has been generated using Coco/R. I have an input statement which I want to test if it provides the desired output using the generated code (Parser.swift).
I haven't tried anything out yet since I don't know where to start.
func Addition {
var x = input.a
var y = input.b
let z: Int?
z = x + y
return z
}
Expected Result:
Input File: a = 10
b = 5
Output: 15

Open XCode , creat new PlayGround:
Then Try this:
import Foundation
struct InputFormat {
var a : Int
var b : Int
}
func addition(input: InputFormat) -> Int {
let x = input.a
let y = input.b
let z = x + y
return z
}
let input = InputFormat(a: 10, b: 5)
print(addition(input: input))
It was the nearest way to get your code into test.
Hope it helps.

Related

What does this function actually do?

i am currently trying to do some self learning in swift just for my own interest. in the course i bought it says that we should create a function similar to this one in order to solve my problem. but I'm blankly staring trying to figure out what this function actually does?
func unknown() -> () -> Int {
var x = 0
let z: () -> Int = {
x += 1
return x
}
return z
}
It is a function that returns another function which will return an integer that will be increased everytime you call it:
let afunc = unknown()
let value1 = afunc() // 1
let value2 = afunc() // 2
let value3 = afunc() // 3
The interesting part of this is the return type. () -> Int is a function that returns an Int, which means that unknown returns a function rather than something simple, like a number.
z is then a variable of that same type and is assigned a function definition to be returned.
If you assign the result of unknown to a variable, you can then invoke the returned function.
This implementation of a high order function is an interesting way of defining generators. An infinite sequence-like class would've achieve the same thing, but with more verbosity:
class MySequence {
private var x = 0
func unknown() -> Int {
x += 1
return x
}
}
var seq = MySequence()
let unknown = seq.unknown
print(unknown()) // 1
print(unknown()) // 2
print(unknown()) // 3
// ... and so on
The main difference between the class and the anonymous closure is the storage for x: the closure captures in due to using the variables within its body, while the class declares explicit storage for the property.
Some fancy stuff can result by using high order functions, like a generator for the Fibonacci numbers:
func fibonnaciSequence() -> () -> Int? {
var a = 0, b = 1
return { let c = a; a += b; b = c; return c }
}
let fibo = fibonnaciSequence()
while let f = fibo() {
// this will print forever
// actually not forever, it will stop at some point due to += overflowing
print(f)
}

Setting an immutable variable with conditional logic in Swift

I have a super simple question on the best way (i.e. style) to do this correctly in Swift.
if a > b {
let x = 1
} else {
let x = 2
}
//then procede to use x
Obviously, this will not work, because the scope of x is only within each branch of the if. But what is the preferred way to go about this, if I want x to be immutable? So far, I have been doing this:
var x:Int
if a > b {
x = 1
} else {
x = 2
}
//then procede to use x
which works, but leaves x as mutable. The next choice is to use the ternary operator as in:
let x = a > b ? 1 : 2
This leaves x immutable but leaves a bit to be desired in terms of readability when the conditions and resulting values become complex. Also, using the ternary solution completely falls down with a more complex example:
if a > b {
let x = 1
} else if b > c {
let x = 2
} else {
let x = 3
}
}
//procede to use x
or this:
switch a {
case 1:
let x = 1
case 2:
let x = 2
default:
let x = 3
}
//procede to use x
Is their any way to promote the scope of a let outward one level, or some other way this type of situation is normally handled?
You can use let in your 2nd example:
let x:Int
if a > b {
x = 1
} else {
x = 2
}
As long as x is fully initialized in all paths, this works.
It works with the switch as well:
let a = 3
let x: Int
switch a {
case 1:
x = 1
case 2:
x = 2
default:
x = 3
}
you can also achieve it using class.
like this
class immutableVariable{
private var value: Any
init(newValue: Any = "") {
self.value = newValue
}
func changeValue(withNewValue newValue: Any){
self.value = newValue
}
func getValue() -> Any{
return value
}
}
and then call it like
let x = immutableVariable()
if a > b{
x.changeValue(withNewValue: 1)
}else{
x.changeValue(withNewValue: 2)
}
and access values using
print(x.getValue())

How can I plot data from a Swift sandbox?

I am practicing with Swift 3.x and I need to plot some data. The problem is that I only really have IBM's online Swift sandbox to work with. The purpose of the plotting is to understand how single-precision code is affected by summations:
I wrote some code to do this, but now I have no clue how to plot this. I doubt Swift can somehow bring up a window for plotting, let alone do so when run through the online sandbox.
Side note: I might be able to VNC into a Mac computer at my university to use Xcode. If I paste the same code into an Xcode project, could it make plots?
Here is the code in case you wanted to see it. I need to now run this code for N=1 to N=1,000,000.
import Foundation
func sum1(N: Int) -> Float {
var sum1_sum: Float = 0.0
var n_double: Double = 0.0
for n in 1...(2*N) {
n_double = Double(n)
sum1_sum += Float(pow(-1.0,n_double)*(n_double/(n_double+1.0)))
}
return sum1_sum
}
func sum2(N: Int) -> Float {
var sum2_sum: Float = 0.0
var n_double: Double = 0.0
var sum2_firstsum: Float = 0.0
var sum2_secondsum: Float = 0.0
for n in 1...N {
n_double = Double(n)
sum2_firstsum += Float((2.0*n_double - 1)/(2.0*n_double))
sum2_secondsum += Float((2.0*n_double)/(2.0*n_double + 1))
}
sum2_sum = sum2_secondsum - sum2_firstsum //This is where the subtractive cancellation occurs
return sum2_sum
}
func sum3(N: Int) -> Float {
var sum3_sum: Float = 0.0
var n_double: Double = 0.0
for n in 1...N {
n_double = Double(n)
sum3_sum += Float(1/(2.0*n_double*(2.0*n_double + 1)))
}
return sum3_sum
}
print("Sum 1:", sum1(N: 1000000))
print("Sum 2:", sum2(N: 1000000))
print("Sum 3:", sum3(N: 1000000))
Yes, #TheSoundDefense is right. There is no plotting output from the Swift Sandbox directly. However, I recommend that you still use the Swift Sandbox. Just run the code, and copy and paste the output in comma-delimited format to Excel or MATLAB to plot it. I did some tweaking to your sum2 as an example, while also making it a bit more functional in the process:
func sum2(N: Int) -> Float {
let a: Float = (1...N).reduce(0) {
let nDouble = Double($1)
return Float((2.0 * nDouble - 1) / (2.0 * nDouble)) + $0
}
let b: Float = (1...N).reduce(0) {
let nDouble = Double($1)
return Float((2.0 * nDouble) / (2.0 * nDouble + 1)) + $0
}
return b - a
}
let N = 10
let out = (1...N).map(){ sum2(N: $0)}
let output = out.reduce(""){$0 + "\($1), "}
print(output)
0.166667, 0.216667, 0.240476, 0.254365, 0.263456, 0.269867, 0.274629, 0.278306, 0.28123, 0.283611,

Generating random numbers with Swift

I need to generate a random number.
It appears the arc4random function no longer exists as well as the arc4random_uniform function.
The options I have are arc4random_stir(), arc4random_buf(UnsafeMutablePointer<Void>, Int), and arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32).
I can't find any docs on the functions and no comments in the header files give hints.
let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)
// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()
You could try as well:
let diceRoll = Int(arc4random_uniform(UInt32(6)))
I had to add "UInt32" to make it work.
Just call this function and provide minimum and maximum range of number and you will get a random number.
eg.like randomNumber(MIN: 0, MAX: 10) and You will get number between 0 to 9.
func randomNumber(MIN: Int, MAX: Int)-> Int{
return Int(arc4random_uniform(UInt32(MAX-MIN)) + UInt32(MIN));
}
Note:- You will always get output an Integer number.
After some investigation I wrote this:
import Foundation
struct Math {
private static var seeded = false
static func randomFractional() -> CGFloat {
if !Math.seeded {
let time = Int(NSDate().timeIntervalSinceReferenceDate)
srand48(time)
Math.seeded = true
}
return CGFloat(drand48())
}
}
Now you can just do Math.randomFraction() to get random numbers [0..1[ without having to remember seeding first. Hope this helps someone :o)
Update with swift 4.2 :
let randomInt = Int.random(in: 1..<5)
let randomFloat = Float.random(in: 1..<10)
let randomDouble = Double.random(in: 1...100)
let randomCGFloat = CGFloat.random(in: 1...1000)
Another option is to use the xorshift128plus algorithm:
func xorshift128plus(seed0 : UInt64, _ seed1 : UInt64) -> () -> UInt64 {
var state0 : UInt64 = seed0
var state1 : UInt64 = seed1
if state0 == 0 && state1 == 0 {
state0 = 1 // both state variables cannot be 0
}
func rand() -> UInt64 {
var s1 : UInt64 = state0
let s0 : UInt64 = state1
state0 = s0
s1 ^= s1 << 23
s1 ^= s1 >> 17
s1 ^= s0
s1 ^= s0 >> 26
state1 = s1
return UInt64.addWithOverflow(state0, state1).0
}
return rand
}
This algorithm has a period of 2^128 - 1 and passes all the tests of the BigCrush test suite. Note that while this is a high-quality pseudo-random number generator with a long period, it is not a cryptographically secure random number generator.
You could seed it from the current time or any other random source of entropy. For example, if you had a function called urand64() that read a UInt64 from /dev/urandom, you could use it like this:
let rand = xorshift128plus(urand64(), urand64())
for _ in 1...10 {
print(rand())
}
let MAX : UInt32 = 9
let MIN : UInt32 = 1
func randomNumber()
{
var random_number = Int(arc4random_uniform(MAX) + MIN)
print ("random = ", random_number);
}
In Swift 3 :
It will generate random number between 0 to limit
let limit : UInt32 = 6
print("Random Number : \(arc4random_uniform(limit))")
My implementation as an Int extension. Will generate random numbers in range from..<to
public extension Int {
static func random(from: Int, to: Int) -> Int {
guard to > from else {
assertionFailure("Can not generate negative random numbers")
return 0
}
return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
}
}
This is how I get a random number between 2 int's!
func randomNumber(MIN: Int, MAX: Int)-> Int{
var list : [Int] = []
for i in MIN...MAX {
list.append(i)
}
return list[Int(arc4random_uniform(UInt32(list.count)))]
}
usage:
print("My Random Number is: \(randomNumber(MIN:-10,MAX:10))")
Another option is to use GKMersenneTwisterRandomSource from GameKit. The docs say:
A deterministic pseudo-random source that generates random numbers
based on a mersenne twister algorithm. This is a deterministic random
source suitable for creating reliable gameplay mechanics. It is
slightly slower than an Arc4 source, but more random, in that it has a
longer period until repeating sequences. While deterministic, this is
not a cryptographic random source. It is however suitable for
obfuscation of gameplay data.
import GameKit
let minValue = 0
let maxValue = 100
var randomDistribution: GKRandomDistribution?
let randomSource = GKMersenneTwisterRandomSource()
randomDistribution = GKRandomDistribution(randomSource: randomSource, lowestValue: minValue, highestValue: maxValue)
let number = randomDistribution?.nextInt() ?? 0
print(number)
Example taken from Apple's sample code: https://github.com/carekit-apple/CareKit/blob/master/CareKitPrototypingTool/OCKPrototyper/CareKitPatient/RandomNumberGeneratorHelper.swift
I'm late to the party 🤩🎉
Using a function that allows you to change the size of the array and the range selection on the fly is the most versatile method. You can also use map so it's very concise. I use it in all of my performance testing/bench marking.
elements is the number of items in the array
only including numbers from 0...max
func randArr(_ elements: Int, _ max: Int) -> [Int] {
return (0..<elements).map{ _ in Int.random(in: 0...max) }
}
Code Sense / Placeholders look like this.
randArr(elements: Int, max: Int)
10 elements in my array ranging from 0 to 1000.
randArr(10, 1000) // [554, 8, 54, 87, 10, 33, 349, 888, 2, 77]
you can use this in specific rate:
let die = [1, 2, 3, 4, 5, 6]
let firstRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
let secondRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
Lets Code with Swift for the random number or random string :)
let quotes: NSArray = ["R", "A", "N", "D", "O", "M"]
let randomNumber = arc4random_uniform(UInt32(quotes.count))
let quoteString = quotes[Int(randomNumber)]
print(quoteString)
it will give you output randomly.
Don't forget that some numbers will repeat! so you need to do something like....
my totalQuestions was 47.
func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{
var arrayOfRandomQuestions: [Int] = []
print("arraySizeRequired = 40")
print("totalQuestions = \(totalQuestions)")
//This will output a 40 random numbers between 0 and totalQuestions (47)
while arrayOfRandomQuestions.count < 40
{
let limit: UInt32 = UInt32(totalQuestions)
let theRandomNumber = (Int(arc4random_uniform(limit)))
if arrayOfRandomQuestions.contains(theRandomNumber)
{
print("ping")
}
else
{
//item not found
arrayOfRandomQuestions.append(theRandomNumber)
}
}
print("Random Number set = \(arrayOfRandomQuestions)")
print("arrayOutputCount = \(arrayOfRandomQuestions.count)")
return arrayOfRandomQuestions as! NSMutableArray
}
look, i had the same problem but i insert
the function as a global variable
as
var RNumber = Int(arc4random_uniform(9)+1)
func GetCase(){
your code
}
obviously this is not efficent, so then i just copy and paste the code into the function so it could be reusable, then xcode suggest me to set the var as constant so my code were
func GetCase() {
let RNumber = Int(arc4random_uniform(9)+1)
if categoria == 1 {
}
}
well thats a part of my code so xcode tell me something of inmutable and initialization but, it build the app anyway and that advice simply dissapear
hope it helps

Functional programming way of doing array conversion

struct MapVector {
var distance: Double
var bearing: Double
}
func distanceAndBearing() -> [MapVector] {
var points = self.mapPoints
var currPoint:CLLocation = points.first!
points.removeAtIndex(0)
var result: [MapVector] = []
for point: CLLocation in points {
let calc = PointCalculator(initialPoint: currPoint, nextPoint: point)
let v = MapVector(distance: calc.pointDistance, bearing: calc.bearing)
result.append(v)
currPoint = point
}
return result
}
I am working in Swift on an application using map coordinates. I have a an array of CLLocations from which I would like to create an array of distances and bearings. The above code (its slightly simplified for readability, so may not be 100% correct) achieves that but I'd like to do it in a neater way. Is this something that can be done with map or filter? Still trying to get my head around the FP way of doing things.
Here is a simplified example for the same problem except the calculations:
let numbers = [3, 7, 2, 8, 3, 7, 5]
let result = numbers.isEmpty ? [] :
map(zip(numbers, numbers[1..<numbers.count])) {
(x, y) in
return (diff: x - y, mult: x * y)
}
result[0].diff // -4
result[0].mult // 21
Here I compute the differences and the multiplications of the numbers.
Note this will work only for Swift 1.2
In case you need it for earlier version, you should explore the use of Zip2.
For reference here are alternative solutions I came up with:-
func distanceAndBearing2() -> [MapVector]
{
// make the removeAtIndex(0) part safe
if (self.mapPoints.count == 0) {
return []
}
var t2 = self.mapPoints
t2.removeAtIndex(0)
let t3 = zip(self.mapPoints, t2)
return Array(t3).map({
(p1, p2) in
return PointCalculator(initialPoint: p1, nextPoint: p2).toMapVector()
})
}
This uses the new zip method from Xcode 6.3 Beta 2, and I moved the conversion to MapVector into the PointCalculator struct
func distanceAndBearing3() -> [MapVector] {
// make the shift part safe
if (self.mapPoints.count == 0) {
return []
}
var points = self.mapPoints
var currPoint = points.shift()!
return points.map {
point in
let initialPoint = currPoint
currPoint = point
return LocationPair(initialPoint: initialPoint,
nextPoint: point).toMapVector()
}
}
And this version uses the same toMapVector method on the PointCalculator struct, but uses a variable outside the map function which is updated by the map function; this feels like its not "correct"