Missing argument for parameter #1 in call to Swift function - ios

Very new to Swift and coding in general.
Just need some help getting my random selector to work. I am trying to make it choose a random number between 1 and 9 and check if that number is the same as the button you click.
enter image description here

I'm guessing you're trying to compare the random number to the title (displayed number) on the clicked button?
If so, add this line above your if statement:
guard let buttonInt = sender.titleLabel?.text.flatMap(Int.init) else { return }
Then, change your if statement to look like so:
if randomNumber == buttonInt {
// do what you want if it matches
} else {
// handle no match
}
// EDIT: Props to Alexander for the flatMap version

Please check :
let rand = Int(arc4random_uniform(9))
guard let buttonInt = Int(sender.currentTitle!) else { return }
if rand == buttonInt {
} else {
}

Related

Valid number between two numbers in a textfield

Allowing only a valid number between x and y to be entered. And display an error message if an invalid number is entered.
I messed around with some if statement and put said x and y numbers in a range, but I don't know how to make that work and display that in lets say a label for example.
I expect the output to be display in a label when a valid number is entered in a text field, when button is pushed. And an error display in a label when an invalid number is enter when the button is pushed.
You can achieve that with the help of several ways. following are can be the best way to get into that.
func validateNumber() {
yourLbl.text = checkNumber(startNumber: 10, endNumber: 20, numberToCheck: 11)
}
I have created a method which is having several ways to do so... you can keep the best one at your convenient
func checkNumber(startNumber: Int, endNumber: Int, numberToCheck: Int) -> String {
//WITH THE HELP OF `~=` operator
if startNumber...endNumber ~= numberToCheck {
return "\(numberToCheck) is within the range of \(startNumber)-\(endNumber)"
} else {
return "\(numberToCheck) is not within the range of \(startNumber)-\(endNumber)"
}
//WITH THE HELP OF .contains mathod
if (startNumber...endNumber).contains(numberToCheck) {
return "\(numberToCheck) is within the range of \(startNumber)-\(endNumber)"
} else {
return "\(numberToCheck) is not within the range of \(startNumber)-\(endNumber)"
}
//WITH THE HELP OF switch statement
switch numberToCheck {
case startNumber...endNumber:
return "\(numberToCheck) is within the range of \(startNumber)-\(endNumber)"
default:
return "\(numberToCheck) is not within the range of \(startNumber)-\(endNumber)"
}
//WITH THE HELP OF if statement
if case startNumber...endNumber = numberToCheck {
return "\(numberToCheck) is within the range of \(startNumber)-\(endNumber)"
} else {
return "\(numberToCheck) is not within the range of \(startNumber)-\(endNumber)"
}
}
check if a range contains a value in Swift
1. Pattern matching operator ~=
func validateRange(_ value : Int) {
if 2..<50 ~= value {
//in range
} else {
// displayLabel.text = "Error message"
}
}
2. .contains method
func validateRange(_ value : Int) {
if (2..<50).contains(value) {
//in range
} else {
// displayLabel.text = "Error message"
}
}
Example :
#IBAction func tappedOnOkButton(_ sender: Any) {
if let value = Int(numberTextField.text) {
validateRange(value)
} else {
// error
}
}

How to check array for contents based off another var, utilize alert window through if statement?

I am currently working on a small Bingo app. I'm having a few issues with this, however.
First off, I have button that when clicked, change images showing that that piece is marked (intended to mark the numbers that have been called). I have an if statement as follows:
if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected {
winConditionLabel.text = "You win!"
func createAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "Bingo!", message: "You win!", preferredStyle: .alert)
let action1 = UIAlertAction(title: "Play Again?", style: .default) { (action) in
self.NewBoardAction(sender)
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action1)
present(alert, animated: true, completion: nil)
}
}
I am having a few issues with this. First off, the Alert window will not come up. Have I done something incorrectly? (This is my first time attempting to use Alerts, so that's very likely.) Secondly, the label, which I have been using to test to make sure that the program gets through the if statement in the first place, only updates after deselecting the final button in the row. This is the main issue I'm trying to fix right now. And lastly, I'm having trouble checking the calledNumbers array (which consists of exactly that - all the numbers that have been called) to make sure that the numbers that have been selected have been called.
I originally had something like this:
if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected && calledNumbers.contains(Int(randomBOne.text)) && calledNumbers.contains(Int(randomIOne.text)) && calledNumbers.contains(Int(randomNOne.text)) && calledNumbers.contains(Int(randomGOne.text)) && calledNumbers.contains(Int(randomOOne.text)) {
// do stuff here
}
But this wouldn't work at all. Is there a better way to do this? I'd really appreciate any help at all!
Pertaining to the issue with checking the array. Here is the code for the first letter. The others do essentially the same thing:
#IBAction func newNumberAction(_ sender: Any) {
// B NUMBERS
let randomLetter = ["B", "I","N","G","O"]
let randomIndex = Int(arc4random_uniform(UInt32(randomLetter.count))) // Gives random number from 0 - 4
if (randomLetter[randomIndex]) == (randomLetter[0]) // if statement for each index/letter possibility {
let randomBIndex = Int(arc4random_uniform(UInt32(listBNumbers.count))) // listBNumbers is the original array that randomizes a number from 1 - 15
if randomBIndex < 1 // makes sure there are still B numbers remaining and if not runs the newNumberAction again {
newNumberAction((Any).self)
} else {
let newBNumber = "\(listBNumbers[randomBIndex])" // creates unique variable for random BNumbers
let combinedNumber = (randomLetter[0]) + newBNumber
var calledBNumbers = [Int]() // creates array for called BNumbers
calledBNumbers.append(Int(newBNumber)!) // adds called B Number into new array
listBNumbers.remove(at: (Int(randomBIndex))) // removes B Number from bank of possible numbers that could be called, this should ensure that no number can be called twice
calledNumbers += calledBNumbers // adds called B Numbers to new array that will be used later to verify BINGO
newNumLabel.text = combinedNumber
// this randomizes the number and combines it with 'B' then displays it in the label's text. This is used to display the next called Number.
}
I know the append is working by checking a label that gives me the count of the variables in the calledNumbers array. Again, I apologize that I didn't provide enough information originally.
Your first problem the alert won't appear because you have the function declared inside of the if statement. Create it outside of the if statement then call it inside the if statement
Your second problem doesn't include enough context in the code for anyone to help you with. How would anyone other then yourself know what the "final button in the row" is?
Your last problem has the same issue as the second problem, "I'm having trouble checking the calledNumbers array". There isn't an array in your question so how can anyone help you with identifying the problem?
This should fix your First problem:
if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected {
winConditionLabel.text = "You win!"
createAlert() // now that this inside of the if statment it will run
}
// this should be declared outside of the if statement
func createAlert() {
let alert = UIAlertController(title: "Bingo!", message: "You win!", preferredStyle: .alert)
// your alert's code
}
You added array information but there still isn't enough context. This is the best I could do based on what I ASSUME you wanted. Your code still isn't clear enough. You should've added all the arrays with foo info. For now I added an array var listBNumbers = ["X", "Y", "Z"] with X,Y,Z as the listBNumbers values to use in your code since you didn't provide anything.
var listBNumbers = ["X", "Y", "Z"]
let randomLetter = ["B", "I","N","G","O"]
/*
// YOUR ORIGINAL CODE
let randomIndex = Int(arc4random_uniform(UInt32(randomLetter.count)))
*/
// 1. TEMPORARILY set this to 0 so that if statement below will run. Delete this and uncomment out your original code above when finished
let randomIndex = 0
if randomLetter[randomIndex] == randomLetter[0] {
/*
// YOUR ORIGINAL CODE
// randomIndex is of type INT there is no need to cast it as Int again in step 7B when your removing it from the listBNumbers array
let randomBIndex = Int(arc4random_uniform(UInt32(listBNumbers.count)))
*/
// 2. TEMPORARILY set this to 2 so that the else statement below will run. Delete this and uncomment out your original code above when finished
let randomBIndex = 2
if randomBIndex < 1 {
// I have no idea what this is
newNumberAction((Any).self)
} else {
// 3. newBNumber is now: Z
let newBNumber = "\(listBNumbers[randomBIndex])"
print("newBNumber: \(newBNumber)")
// 4. combinedNumber is now: BZ
let combinedNumber = randomLetter[0] + newBNumber
print("combinedNumber: \(combinedNumber)")
// 5. THIS IS AN ARRAY of type INT it will not accept Strings
var calledBNumbers = [Int]()
// 6A. newBNumber is of type STRING not a type INT. This line below CRASHES because what your saying is calledBNumbers.append(Int(Z)!). How can you cast a Z to an Int?
calledBNumbers.append(Int(newBNumber)!) // newBNumber contains the letter Z
// 6B. THIS IS MY ASSUMPTION seems like you wan to use
calledBNumbers.append(randomBIndex)
print("calledBNumbers: \(calledBNumbers.description)")
// 7A. check to see if the index your looking for is inside the listBNumbers array
if listBNumbers.indices.contains(randomBIndex){
// 7B. randomBIndex is ALREADY of type Int. Why are you casting it >>>Int(randomBIndex)
listBNumbers.remove(at: randomBIndex)
print("listBNumbers: \(listBNumbers.description)")
}
// 8. There is no context for me to even try and figure out what calledNumbers is so I can't give you any info about it
calledNumbers += calledBNumbers
// combinedNumber contains: BZ from the step 4 so that is what your newNumLabel.text will show
newNumLabel.text = combinedNumber
}
}
Here's a way to clean up this code so it's more readable. You need to break all of that down into smaller functions so its more readable:
if areButtonsSelected() == true && doesCalledNumbersContainBingo() == true{
// do stuff here
}
func areButtonsSelected() -> Bool {
if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected{
return true
}
return false
}
func doesCalledNumbersContainBingo() -> Bool {
let b = Int(randomBOne.text)
let i = Int(randomIOne.text)
let n = Int(randomNOne.text)
let g = Int(randomGOne.text)
let o = Int(randomOOne.text)
if calledNumbers.contains(b) && calledNumbers.contains(i) && calledNumbers.contains(n) && calledNumbers.contains(g) && calledNumbers.contains(o){
return true
}
return false
}

If using "ActiveLabel.swift" to tag words have space, it'll fail to tag - swift

I have a question to tag person's name using ActiveLabel.swift.
But I face a problem.
If person's name have space, it will fail to tag all name with space.
What's wrong with me?
Have any good idea to me?
Thanks.
myLabel.customize { (label) in
label.text = "#Kevin k Hello"
label.handleMentionTap({ (mentionString) in //mentionString = Kevin
guard self.tagsLabelDic[mentionString] != nil else { return } // self.tagsLabelDic = ["Kevin k": "appname://app/user/aa445cfaef786864044f12e2"]
guard let url = URL(string: self.tagsLabelDic[mentionString]!) else { return }
self.taggedDelegate?.tagsLabelClicked(url: url)
})
}
It seems you have to use a custom type
Something like this:
let customType = ActiveType.custom(pattern: "\\s#Kevin\\sk\\sHello")

Facing error as invalid literal for int () with base 10: in swift 2

As per screenshot while am submitting the feedback facing this issue. Any help is appreciated.
I have to enter comments like smile or sad after that am typing some text about the ride. Everything was working fine. While I am clicking on submit button I am getting journeyId as nil other than that in self.journeyAPIdetails I am getting the whole data from JSON. Thanks in advance.
func submitButtonTapped() {
if self.smileActive! == true || self.frownActive! == true {
let comment = (self.mainView.textfield.text! == "Tap to Type" || self.mainView.textfield.text! == "Leave any additional Comments here") ? "": self.mainView.textfield.text!
let rating = self.smileActive! == true ? "true":"false"
let journeyId = self.journeyAPIdetails!["data"]["journey_id"].stringValue
let userId = AccountService.sharedInstance.typeOfUser() == .Customer ? self.journeydetails?.driver.id : self.journeydetails?.customer.id
let details = ["rating":rating, "comment":comment, "journey_id":journeyId]
JourneyService().rateAUser(details).onSuccess { (json) -> Void in
if json["status"].stringValue == "success" {
print("dismissViewControllerAnimate")
self.dismissViewControllerAnimated(true, completion: nil)
AccountService.sharedInstance.clearJourneyContent()
} else if json["status"].stringValue == "fail" {
print("dismissViewControllerAnimated")
self.displayAlert("Error", message: json["message"].stringValue)
}
}
}
else {
super.displayAlert("Feedback", message: "Give some feedback and optionally add some comments.")
}
}
}
invalid literal for int () with base 10: '' is the error message from Python indicating you want to convert an empty string to an integer. This means the server expects a string that contains decimal digits, but you give it an empty string instead. This points to details having wrong input, in particular the journeyId field.
After discussing with OP, we find out the problem is in self.journeyAPIdetails!["data"]: it is an array containing an single object, but OP didn't notice it. So the solution is to change that line to:
let journeyId = self.journeyAPIdetails!["data"][0]["journey_id"].stringValue
// ^^^
Moral of the story: be careful to analyze the structure of the JSON you send and receive.

Swift call random function

I got 3 different functions and I want to call one of these randomly.
if Int(ball.position.y) > maxIndexY! {
let randomFunc = [self.firstFunction(), self.secondFunction(), self.thirdFunction()]
let randomResult = Int(arc4random_uniform(UInt32(randomFunc.count)))
return randomFunc[randomResult]
}
With this code I call all functions, and the order is always the same. What can I do to just call one of these?
The reason the three functions are called (and in the same order) is since you are causing them to be called when you put them in the array.
This:
let randomFunc = [self.firstFunction(), self.secondFunction(), self.thirdFunction()]
Stores the return value of each function in the array since you are invoking them (by adding the '()').
So at this point randomFunc contains the return values rather than the function closures
Instead just store the functions themselves with:
[self.firstFunction, self.secondFunction, self.thirdFunction]
Now if you want to call the selected method do not return its closure but invoke it:
//return randomFunc[randomResult] // This will return the function closure
randomFunc[randomResult]() // This will execute the selected function
if Int(ball.position.y) > maxIndexY! {
let randomNumber = Int.random(in: 0...2)
if randomNumber == 0 {
firstFunction()
} else if randomNumber == 1 {
secondFunction()
} else if randomNumber == 2 {
thirdFunction()
}
}
I expect it should work
if Int(ball.position.y) > maxIndexY! {
let randomFunc = [self.firstFunction, self.secondFunction, self.thirdFunction]
let randomResult = Int(arc4random_uniform(UInt32(randomFunc.count)))
return randomFunc[randomResult]()
}

Resources