Search code examples
swiftnsuserdefaultsuserdefaults

Allowing User to Create a Key and Value in Swift userdefaults


I currently have my app adding a value to two different keys in userDefaults the values being added are a "Song Name" and the "BPM" (beats per minute) the two keys are sName and sBPM.

What I want to do is let the user create the Key with the song name and the value being the BPM. which would allow them to select a song from a UiPickerView and the app could display the BPM.

Basically. How do i let the user create a key from a text input rather than giving a value to a pre created key.

Hopefully this makes sense. I am very new to Swift and programming in general


Solution

  • Considering you have a UITextField on your UI for entering both Song Name and BMP Value, with a reference to it in your code as songTextField and bmpTextField respectively, when return Key is Tapped or whenever you want to perform the operation, you can use the below code

    if let songName = songTextField.text, let bmpValue = bmpTextField.text {
        UserDefaults.standard.set(bmpValue, forKey: songName)
    }