<!--
{
  "availability" : [
    "iOS: 4.0.0 -",
    "iPadOS: 4.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.6.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/UserDefaults/set(_:forKey:)-2bqjt",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSUserDefaults(im)setURL:forKey:"
  },
  "title" : "set(_:forKey:)"
}
-->

# set(_:forKey:)

Sets the value of the specified key to a URL.

```
func set(_ url: URL?, forKey defaultName: String)
```

## Parameters

`url`

The value to store in the defaults database.

`defaultName`

The key that contains the setting’s name.

## Discussion

This method handles file URLs differently than other types of URLs. For most URLs, the
method stores the URL object as the root object of a [`Data`](/documentation/Foundation/Data)
archive. If `url` contains a path to a file in the home directory, this method replaces
the home directory portion of the path with a tilde (~) character before generating
the data object. When you read the value back, the system expands the tilde character
to the current home directory path.

If the location of a file might change, don’t use a file URL to specify its location.
Instead, create a bookmark URL using the [`bookmarkData(withContentsOf:)`](/documentation/Foundation/NSURL/bookmarkData(withContentsOf:))
method and save that URL instead. Bookmark URLs store additional information about the file
so the system can locate the file later, even if the path to that file changes.

After you call this method, the system generates a [`didChangeNotification`](/documentation/Foundation/UserDefaults/didChangeNotification)
for registered observers.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)