Swift exit IBAction func in if - ios

Im trying to end a funtion of an IBAction in an if statement, after validation input.
I've made a (global) function to check if the values of the variables which contain user input are Integers. Im trying to exit the functon by returning nothing, but the function doesn't end.
#IBAction func calculate(sender: AnyObject) {
var objects: [Int?] = [] // Contains an array of variables to be checked
//Global.checkInt returns true if all the variables in the array are int
//Global.throwLocalNot Global function to show a local notification
if Global.checkInt(objects) == false{
Global.throwLocalNot("Error", description: "Check your input!", viewController: self)
return
}
// Code to be executed if all variables are integers
...
}
This code works and throws a local notification if the input is not correct, but the return does not seem to work. What is the best way to stop a function from further execution?

Related

Xcode 8/Swift 3: Reset all variables to initial values

When a gameOver() function is triggered, I would like all variables to reset to their original, unchanged values (as in, the values that are assigned in the ViewController file) when a user presses a Restart button. How can I do this?
Depending on the specific variables you have, one solution would be to create a struct with the fixed initial values and assign those to your active game variables in the Restart function.
You can define a function that reset the variables to the default value like this :
func resetGame(){
score = 0 // or default value
life = 3 // or default value
//.... and so on
}
Assume the restart button are connected to this function
#IBAction func restartGame(sender: UIButton){
gameOver()
resetGame()
}
you can call this function after calling gameOver() inside the restart button function.
If your question is about how to declare default values you can use struct as Jay said like this :
struct DefaultValues {
let score = 0
let lifes = 3
let level = 1
}
and resetGame() will be like this :
func resetGame(){
score = DefaultValues().score
life = DefaultValues().life
level = DefaultValues().devel
}

What is a difference between instantiate a class?

Everyone,
I'm trying to understand why the exemple 1 return nil ( don't call a goooo function ), and the second exemple call it. Do I need to do something extra ?
Exemple 1 :
class A: UICollectionViewCell {
var exempleOneDetail: ExempleOneDetail?
...
}
func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
self.exempleOneDetail?.goooo(imageView)
}
=>> Result Nil
Exemple 2 :
func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
let exempleOneDetail = ExempleOneDetail()
exempleOneDetail?.goooo(imageView)
}
=>> Result : Call de function goooo
Thanks for help,
Regards
In example 1, you're never setting exempleOneDetail to anything before you call goooooo() on it, so it's nil.
In example 2, you're creating a local variable called exempleOneDetail and assigning an initialized object to it, and then calling goooooo(), so it does what you expect. However, be aware that your local copy, because it has the same name as the instance variable, is shadowing that variable, and if you try to use exempleOneLabel anywhere outside of handleZoomTap(), it will still be nil because you never assigned anything to it.

How do I use variable declarations within a function outside of the function in Swift?

I am new to programming and could not find out how I might get the variable data back out of the function I created in swift. I tried returning the variable however I get an error in the compiler.
class ViewController: UIViewController {
#IBOutlet var textField: UITextField!
var userName = String()
#IBAction func returnPressed(_ sender: Any) {
userName = textField.text! //user input will = userName
print("return pressed inside textfield")
print("User name set to \(userName)")
self.view.endEditing(true) //hides keyboard
return (userName)
}
The function activates via the return being button pressed. The variable userName will then equal the users input within the text field.
The problem is that outside of this function, I can no longer call on the variable userName and receive the user input value that was stored earlier.
And I cant seem to get the "return" to work like ive been reading.
First of all userName is an internal variable for your class ViewController and can be accessed in every function. You have to access the variable within some function like viewDidLoad, viewWillAppear or any of your custom function within your class.
Make any function and access the variable
func test() {
//access here userName
}
All entities in your code (with a few specific exceptions) have a default access level of internal if you do not specify an explicit access level yourself. As a result, in many cases you do not need to specify an explicit access level in your code.
Read more about Access Controls.
Also you are returning something from an IBAction of the button which don't have any return type. You will get a compiler error there.
Generally return of textfields is handled by UITextFieldDelegate. See here.
The delegate method in Swift 3 is
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
The function's return statement isn't doing anything because you are not declaring the function as returning anything.
func returnPressed(_ sender : Any) -> String
That would be a function that returns a String.
In this case, you don't need a return statement because you are not capturing the function's result anywhere by calling the function manually.
If you print the value of userName elsewhere in your code after pressing Return, the variable will have captured that value, please make sure to try before saying you're sure it's not working :)

How to find value of UIImage called in ViewDidLoad, pass to another function in Swift

I am using a simple function to call a random image when a view controller is loaded.
override func viewDidLoad() {
super.viewDidLoad()
var randomtest = ReturnRandom()
mainImage.image = UIImage(named: randomtest)
}
I want a button's action to be based on what image was displayed. For example
#IBAction func Button1(sender: AnyObject) {
switch randomtest {
case 1: //Do something here
case 2: //Do something different here
default:
}
However I can not figure out how to get the value of "randomtest" out of ViewDidLoad. I also can not seem to create the random number outside the ViewDidLoad then pass the variable in. Sorry I'm new to all this, iOS development is a long way away from php...
The reason I was having trouble declaring the result of my function as a instance variable is that my function is also an instance function. I can not call it, there has been no instance. So this
class ViewController : UIViewController {
var randomtest: Int = ReturnRandom();
Will return a "Missing argument for parameter #1 in call"
For more details please check out this very helpful thread on setting initial values. Since my function was so simple I just computed the property while setting the initial value, no need for an additional class level function.
dynamic var randomtest:String {
let imageNumber = arc4random_uniform(3)
var imageString = String(imageNumber)
return (imageString)}
Hope this helps someone.

Swift: permanent variable change through global files

I am working in between three files: Menu.swift, Main.swift and Game.swift.
In my Main.swift, I define the variable swipeNumber:
class Main {
var swipeNumber: Int = 0 {
didSet{
println("The new swipe number is \(swipeNumber)")
}
}
}
N.B. It is in a class so that I can reference the variable from other files, and the didSet property observer will function.
As you can see, its initial value (I think) is 0.
Then, in my Menu.swift, I retrieve the information from the Main class in Main.swift.
let main = Main()
I then have three buttons, which will, on touch, change the swipeNumber variable, based on which button was pressed.
class Menu: UIViewController {
#IBAction func pressedThreeSwipes(sender: AnyObject) {
main.swipeNumber = 3
}
#IBAction func pressedFiveSwipes(sender: AnyObject) {
main.swipeNumber = 5
}
#IBAction func pressedTenSwipes(sender: AnyObject) {
main.swipeNumber = 10
}
//...
}
When I run the program, my property observer appears to work, printing messages such as:
The new swipe number is 3
The new swipe number is 5
The new swipe number is 10
And in the Game class, (for troubleshooting purposes), I have another property observer, checking the integer of the variable swipeNumber when the button test is pressed:
class Game: UIView {
let main = Main()
func didMoveToView(view: UIView) {
/* Setup your scene here */
println("now")
println("\(main.swipeNumber)"
//Nothing happens here, suggesting that didMoveToView is failing
}
#IBAction func test(sender: AnyObject) {
println("\(main.swipeNumber)")
}
}
My func test prints a number, but sadly that number is not 3, 5, or 10. It's 0.
I think that the problem lies with my variable in Main.swift, however I am not sure.
Any advice or 'fixes', whether quick or lengthy, would be very greatly appreciated.
Thank you,
Will
You have different instances of your class Main, and they each carry a different value for the same properties.
You should try the Singleton pattern (see e.g. here or here).
When you call Main(), you are creating a new object...emphasis on NEW. It has no knowledge of what you've done to other objects of the same type. If you want to use the same object in different places, you need to make it a parameter and pass it into methods rather than creating a different object.

Resources