0

I'm so stuck with my beginner coding project. Editor placeholder in source file error need to unwrap optional string

My app is a fitness tracker just to track PB's but I can't get it, to store the values inputted once the app closes. I have created the array of the options but I can't seem to figure out how to unwrap the code for the string "newText"

    textFields = [benchPressPB, squatPB, deadliftPB, ohpPB, rackPullPB, legPressPB, pullUpsPB]
     
        for (index, key) in textFieldKeys.enumerated() {
            let aValue = UserDefaults.standard.string(forKey: key)
            textFields[index].text = aValue
            textFieldStrings.append(aValue ?? "")
        }
        
    }



    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        let newText = textField.text
        if let index = textFields.firstIndex(of: textField) {
            textFieldStrings[index] = newText
           UserDefaults.standard.set(newText, forKey: textFieldKeys[index])
        }
        return true
    }

}

small4
  • 3
  • 2

2 Answers2

0

You can also unwrap it in the if let ... = .... To find out why the if condition is separated by a comma, see this post.

Code:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    if let index = textFields.firstIndex(of: textField), let newText = textField.text {
        textFieldStrings[index] = newText
        UserDefaults.standard.set(newText, forKey: textFieldKeys[index])
    }
    return true
}
George
  • 25,988
  • 10
  • 79
  • 133
0

The "placeholder in source code" error is from Xcode's auto-fill.

As you type a method name, Xcode fills out templates for the various classes and functions you enter. Those templates include "placeholders" for the various parameters. The editor displays them as colored text, and when you tap on a placeholder, it lets you replace it with actual code.

An example of a function template with placeholders:

UIView.animate(withDuration: <#T##TimeInterval#>, delay: <#T##TimeInterval#>, options: <#T##UIView.AnimationOptions#>, animations: <#T##() -> Void#>, completion: <#T##((Bool) -> Void)?##((Bool) -> Void)?##(Bool) -> Void#>)

The <#T##TimeInterval#> bit is a placeholder for the string "TimeInterval"

It looks like this in the Xcode editor:

enter image description here

Duncan C
  • 128,072
  • 22
  • 173
  • 272