Generating a random number under super.ViewDidLoad - ios

I am making a 'Guess The Number' Game for a project at school, I want my application to generate one random number between 1-10 and then let me use it under my button which allows the user to guess the number by entering their guess into a text field. I have managed to do some of this, my random number generator is currently under my 'Guess' Button which means every time they press the button the number will change. My solution is to generate a number under super.viewDidLoad and then use it under the button to do the rest, but I'm not sure how to do this.

If I've understood you correctly you want the number to be generated only once instead of on every press.
So you might want something like this:
var randomNumber: Int
override func viewDidLoad() {
super.viewDidLoad()
//Initialization
generateRandomNumber()
}
func generateRandomNumber() {
randomNumber = Int(arc4random_uniform(9)) + 1
}
randomNumber is an instance-variable, so you can access it in all of your methods, for example to check if the user guessed correctly.

Use the standard library functions for high quality random numbers: arc4random() or arc4random_uniform(), just as in Objective-C.
They are in the Darwin module, so you will need to import Darwin if you haven't imported AppKit, UIKit, or Foundation.

Related

Converting integer so it has two decimal places in Swift

I have a variable called 'totalMonthly like follows:
var totalMonthly: Float = 0.00
I then have a function which gets called on viewDidLoad which pulls an array of values from an API request, and loops through them, adding them on to the totalMonthly variable.
This function also contains a Dispatch so that I can render the variable on my screen upon page load inside of a monthlyLabel text label.
func calculateMonthly() {
for account in accounts {
totalMonthly += Float(account.repaymentTotal)!
print(account.repaymentTotal)
}
DispatchQueue.main.async {
print(self.totalMonthly)
self.monthlyLabel.text = "£\(self.totalMonthly)"
}
}
However, the values are always showing with just one decimal place - for example it might be 690.0, or 720.2.
I want them instead to display as 690.00, or 720.20.
I have tried converting it into a %.2f format as a string, but that just automatically makes the variable change to 0.00 and render that on the screen.
For reference, the values pulled from the API are stored as flat values (230, 540 etc), so I figured I'd need to convert them into floats, but no luck.
Can anyone point out what I'm doing wrong here?

what's the use of .count command in repeat while loop?

I recently began to study swift as my first programming language and there's a very simple term that i can't find an answer for it.
take a look at this code:
var a = [Int]()
repeat {
let randomNumbers = Int.random(in: 0...10)
if a.contains(randomNumbers) == false {
a.append(randomNumbers)
}
print(randomNumbers)
} while (a.count < 10)
so this code is supposed to add 10 numbers (no duplicates) from 0...10 into the array until all unique integers are listed. what I don't understand is the role of "while" here.
doesn't the last line mean the number of "generated numbers" must be less than 10? then why every time I run the code I get more than 10 numbers (say 30-40) in the console?
Also according to the code, this code must not generate dupes. then why do I get some numbers printed 2,3 times in the console?
you check if randomNumbers already added to array a, if yes, the loop will be executed again, until a.count < 10.
if you move the print statement inside the if statement, it will be printed exactly 10 times.

Int Variable won't let me add data from UI text field

I'm currently working on making a savings app in Xcode 10. I'm working on a feature that lets users add the amount of money they have saved for something into the app through a UI text field. I can't find a way to return the text from the text field to an Integer and add that to the total sum of money that has been saved. Also whenever I tried to add a test variable I got plenty of errors.
var amountSavedSoFar += amountOfMoneySaved
Both I have set to be integers. I'm trying to set amountOfMoneySaved equal to the numbers in the text field, but it doesn't seem to work.
'+=' is not a prefix unary operator
Consecutive statements on a line must be separated by ';'
Type annotation missing in pattern
Unary operator cannot be separated from its operand
You've got a few issues as you mentioned:
amountSavedSoFar is declared in the saveAmount function and will not be persisted if you call that function more than once.
amountSaved.text is not being converted from String to the appropriate type (Int, Double, etc.)
amountSavedSoFar isn't typed or initialized.
Try something like:
var amountSavedSoFar: Int = 0
#IBAction func saveAmount(_ sender: Any) {
//Convert the text and default to zero if conversion fails
amountSavedSoFar += Int(amountSaved.text) ?? 0
}

Call Directory Extension CallKit does't recognize numbers with more than 9 digits

I'm working with CallKit and developing an app with a Call Directory Extension. I've followed this tutorial and I'm currently test the capability of identify numbers that the user does't have in his contacts and show an ID from my app, but although is working perfectly with numbers of 1 to 9 digits, for example 123456, when I set numbers with 10 or more digits, iOs doesn't recognize the number. After a day and a half of google it, I've have found no information about that. If anyone can help me I'll appreciate it. Thanks in advance.
The method for set the phone numbers for recognize:
private func addAllIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
// Retrieve phone numbers to identify and their identification labels from data store. For optimal performance and memory usage when there are many phone numbers,
// consider only loading a subset of numbers at a given time and using autorelease pool(s) to release objects allocated during each batch of numbers which are loaded.
//
// Numbers must be provided in numerically ascending order.
let allPhoneNumbers: [CXCallDirectoryPhoneNumber] = [ 123456789, 1_888_555_5555 ]
let labels = [ "ID test", "Local business" ]
for (phoneNumber, label) in zip(allPhoneNumbers, labels) {
context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: label)
}
}
With this code, when I simulate a call with the number 123456789, iOS shows the tag "ID test" and that's correct, but if I add any digit, for example 0 at the end: 1234567890, iOS does't show anything when I simulate a call. I don't know if I'm missing something.
Well, after a bunch of tests I could made it work. The point was that the phone must contain the full country code and the area code. So for example 00_52_55_4567_8932 877 or +52_55_4567_8932 both will work. But 55_4567_8932 and 4567_8932 will not work. I hope this can help someone else in the future. Thank you all!

Cropping MIDI file using AudioKit

I am trying to crop and loop a certain part of a MIDI file using AudioKit.
I am using a sequencer and found a couple of things that are close to what I need, but not exactly.
I found a method in AKSequencer called clearRange. With this method I am able to silence the parts of the MIDI I don't want, but I haven't found a way to trim the sequencer and only keep the part I am interested in. Right now only the part I want has sound but I still get the silent parts.
Is there a way to trim a sequencer or to create a new sequencer with only the portion I want to keep from the original one?
Thanks!
One frustrating limitation of Apple's MusicSequence (which AKSequencer is based on) is that although you can easily set the 'right side' of the looping section, the left side will always loop back to zero and cannot be changed. So to crop from the left side, you need to isolate the section that you want to loop and shift it over so that the start of your loop is at zero.
As of AudioKit 4.2.4, this is possible. Use AKMusicTrack's .getMIDINoteData() to get an array of AKMIDINoteData structs whose content can be edited and then used to replace the original data. If you had a 16 beat track and you wanted to loop the last four beats, you could do something ike this:
let loopStart = 12.0
let loopLength = 4.0
// keep track of the original track contents
let originalLength = 16.0
let originalContents = track.getMIDINoteData()
// isolate the segment for looping and shift it to the start of the track
let loopSegment = originalContents.filter { loopStart ..< (loopStart + loopLength) ~= $0.position.beats }
let shiftedSegment = loopSegment.map { AKMIDINoteData(noteNumber: $0.noteNumber,
velocity: $0.velocity,
channel: $0.channel,
duration: $0.duration,
position: AKDuration(beats: $0.position.beats - loopStart))
}
// replace the track contents with the loop, and assert the looping behaviour
track.replaceMIDINoteData(with: shiftedSegment)
seq.setLength(AKDuration(beats: loopLength))
seq.enableLooping()
// and to get back to the original:
track.replaceMIDINoteData(with: originalContents)
seq.setLength(AKDuration(beats: originalLength))
seq.enableLooping()
If you wanted to looping section to repeat for the length of the original sequence, then you could use the shiftedSegment as a template and build a 16 beat sequence from it.

Resources