Share variables between functions in Swift - macos

I started Swift today.
I have no idea how to share variables between functions. Does anyone have an idea?
#IBAction func function1(sender : NSButton) {
var variable1 = 1
}
#IBAction func function2(sender: NSButton) {
println(variable1)
}
I googled about this, but I couldn't find the solution.
I'm using Xcode6 beta6.
----EDITED----
The specific thing I wanted to do was the code below.
var files: [AnyObject] = [AnyObject]()
#IBAction func selectFiles(sender : NSButton) {
let openDlg = NSOpenPanel()
openDlg.allowsMultipleSelection = true
openDlg.canChooseFiles = true
openDlg.canChooseDirectories = true
if openDlg.runModal() == NSOKButton{
var files = openDlg.URLs
}
}
#IBAction func startScript(sender: NSButton) {
for var i = 0; i < files.count; i++ {
var fileName:AnyObject = files[i];
println(files[i])
}
}
In fact, I wanted to open a dialog to select files, and log the paths of those files.
No error occurs in this code, but nothing is printed. How can I do so?

Why are you not declaring variable1 outside and then use it in both of your functions as shown below:
var variable1 = 0
#IBAction func function1(sender : NSButton) {
variable1 = 1
}
#IBAction func function2(sender: NSButton) {
println(variable1)
}
EDIT:
Based on the new code you posted, you are doing
var files = openDlg.URLs
Here, you are declaring a local variable and not using your global one.
Remove the var from here and keep only
files = openDlg.URLs

Related

UserDefault in Xcode is not saving the text

This code won't save the text for same reason. How to fix it?
import UIKit
class ViewControllertextview: UIViewController {
#IBOutlet weak var text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
_ = UserDefaults.standard
let value = UserDefaults.standard.string(forKey: "onekey")
if value != nil{
text.text = value
}
else {
text.text = "Here you can make Notes"
}
}
let defaults = Foundation.UserDefaults.standard
#IBAction func Sbutton(_ sender: Any) {
UserDefaults.standard.set(text.text, forKey: "onekey")
}
#IBAction func ggbutton(_ sender: Any) {
}
}
UserDefaults don't immediately write data to storage. You can try calling UserDefaults.standard.synchronize() to save immediately, right after UserDefaults.standard.set(..

Found nil while unwrapping an optional value - Swift 2

I am getting this error which I cannot explain:
#IBOutlet weak var licencePlateLabel: UILabel!
var editItem: CarValues? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let editedCar = self.editItem {
if let licencePlate = self.licencePlateLabel {
licencePlate.text? = editedCar.licencePlate!//this gives me nil
}
else {
print("value was nil")
}
print(editedCar.licencePlate!)//this is giving me the correct value
}
if I replace the
if let licencePlate = self.licencePlateLabel {
licencePlate.text! = editedCar.licencePlate!
}//this throws an error "found nil......"
even if I do this I m still getting the "found nil..."
func configureView() {
licencePlateLabel.text = "test"
[...]
}
BUT if I put the above on viewDidLoad then it works fine
override func viewDidLoad() {
licencePlateLabel.text = "test"
[...]
}
What is going on in this code?
EDIT
I am passing the value of the editItem from the detailView to the EditView like this:
#IBAction func editButtonTapped(sender: AnyObject) {
let storyBoard = UIStoryboard(name: "Main", bundle:nil)
let editScreen = storyBoard.instantiateViewControllerWithIdentifier("ID_EditViewController")
self.navigationController?.pushViewController(editScreen, animated: true)
let controller = EditViewController()
controller.editItem = detailItem
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
You don't unwrap properties to set them, only to read from them. So your code can simply be:
if let licencePlate = self.licencePlateLabel {
licencePlate.text = editedCar.licencePlate
}
Note that because licencePlate.text is an optional value anyway, there is also no need to unwrap editedCar.licencePlate. It's ok to use its value whether it is nil or contains a String.

swift Detect the correct textfield to add an attribute

i´m writing an input text quiz app, and i have an array of Int where i can store if answer was correct or not with 0 or 1 and also i have 3 textfields where i write the answers, and i want to change the textfields back ground color to red or green depending on the answers variable ,, if index variable its 1 change color to green and if is 0 change color to red.. this is what i have
#IBOutlet var textField1: UITextField!
#IBOutlet var textField2: UITextField!
#IBOutlet var textField3: UITextField!
//change int to 1 if answer was correct (3, ea for each textfield)
var answers = [0,0,0]
#IBAction func button(sender: AnyObject) {
for (index, answer) in goodAnswers.enumerate() {
print (answer)
if answer != 0 {
print ("ok")
} else {
print("not ok")
}
}
}
thanks !
You need something like this:
var goodAnswers = ["One", "Two", "Three"]
var textFields:[Int:UITextField]!
override func viewDidLoad() {
super.viewDidLoad()
self.textFields = [0:textField, 1:textField2]
}
#IBAction func btnClick(sender: AnyObject) {
for(index, answer) in goodAnswers.enumerate() {
if textFields[index]?.text == answer {
textFields[index]?.backgroundColor = UIColor.greenColor()
}
else {
textFields[index]?.backgroundColor = UIColor.redColor()
}
}
}
UPDATE:
If you want to have another good answers simply change your code to like this:
Declare new property:
var collectionOfGoodAnswers: [Int : [String]]!
and in viewDidLoad() method:
self.collectionOfGoodAnswers = [0: ["Hello", "World"],
1: ["Welcome", "Friend"]]
and then implement the click action:
#IBAction func btnClick(sender: AnyObject) {
for(index, _) in collectionOfGoodAnswers.enumerate() {
guard let goodAnswer = collectionOfGoodAnswers[index] else { return }
guard let answer = textFields[index] else { return }
guard let text = answer.text else { return }
if goodAnswer.contains(text) {
textFields[index]?.backgroundColor = UIColor.greenColor()
}
else {
textFields[index]?.backgroundColor = UIColor.redColor()
}
}
}
hope it helps.

What does the underscore mean in this case?

my code before the migation to Swift 2.0:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "RhymeFavoriten") {
// pass data to next view
let dest = segue.destinationViewController as! FavoritenViewController
let source = segue.sourceViewController as! RhymeViewController // !!!!!!
dest.favoritenType = 1
dest.delegate = self
}
}
the migration told me to change it to
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "RhymeFavoriten") {
// pass data to next view
let dest = segue.destinationViewController as! FavoritenViewController
_ = segue.sourceViewController as! RhymeViewController // !!!!!!!!!!
dest.favoritenType = 1
dest.delegate = self
}
or
func textSelected(selectedText:String, selectedType:Int) {
var fullTextArr = text.componentsSeparatedByString("\n")
var myArray = [String]() // !!!!!!
to
func textSelected(selectedText:String, selectedType:Int) {
var fullTextArr = text.componentsSeparatedByString("\n")
_ = [String]() // !!!!!!!!!
I can´t see, what is _ = standing for :-(
_ is a placeholder. It means that the values assigned to _ are ignored.
Xcode's migration tool made this changes because it has detected that you didn't use source or myArray anywhere, thus replaced these variables by the placeholder.
Now instead of being assigned to a variable, the returning result of segue.sourceViewController as! RhymeViewController and the returning result of [String]() are ignored.
The returning result is ignored but the expression is still evaluated at runtime: if it has side effects, these effects will occur.
So if you actually don't need these instructions you should get rid of them entirely.

errors while trying to compare a string to element in array

let verbList: [String] = ["hacer", "ser", "estar"]
let POVList: [String] = ["él / usted","ella / usted","ellas / ustedes","ellos / ustedes","tú","yo","nosotros",]
let correctConjugation: [[String]] = [["hace","hace","hacen","hacen","haces","hago","hacemos"], ["es","es","son","son","eres","soy","somos"], ["está","está","estan","estan","estas","estoy","estamos"]]
func randomVerb() -> Int { //creates and returns a random number for the prefix arrray
var randomVerb = Int(arc4random_uniform(3))
return randomVerb
}
func randomPrefix() -> Int { //creates and returns a random number for the verb array
var randomPrefix = Int(arc4random_uniform(7))
return randomPrefix
}
#IBAction func changeVerb(sender: AnyObject) {
Verb.text = verbList[randomVerb()]
POV.text = POVList[randomPrefix()]
userResponse.backgroundColor = UIColor.whiteColor()
userResponse.text = ""
}
#IBAction func checkResponse(sender: AnyObject) {
var userResponseA: String
userResponseA = userResponse.text
if (userResponseA == correctConjugation[randomVerb()[randomPrefix()]]){
userResponse.backgroundColor = UIColor.greenColor()
} else {
userResponse.backgroundColor = UIColor.redColor()
}
}
So I get two errors here (in the if statement in checkResponse): first, "int does not have a member named 'subscript'" and if I just take out the call for the function in the if statement I get: "'String' is not convertible to 'Mirror Disposition'"
I really have no idea why this is not working. Bear with me, as I am an Xcode noob just trying to get a better grade in spanish.
Very close - just need to have your subscripts separated:
if (userResponseA == correctConjugation[randomVerb()][randomPrefix()]) {
// ...
}
When working with an array of arrays (in this case correctConjugation), each subscript takes you one level down.
For the other issue, you want a couple variables to hold the current verb and prefix indexes:
class VC: UIViewController {
// list declarations here
var verbIndex = 0
var povIndex = 0
#IBAction func changeVerb(sender: AnyObject) {
verbIndex = randomVerb()
povIndex = randomPrefix()
Verb.text = verbList[verbIndex]
POV.text = POVList[povIndex]
userResponse.backgroundColor = UIColor.whiteColor()
userResponse.text = ""
}
#IBAction func checkResponse(sender: AnyObject) {
var userResponseA = userResponse.text
if (userResponseA == correctConjugation[verbIndex][povIndex]){
userResponse.backgroundColor = UIColor.greenColor()
} else {
userResponse.backgroundColor = UIColor.redColor()
}
}
}

Resources