skip to Main Content

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
    }

}

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search