---
title: "write(to:atomically:encoding:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/nsstring/write(to:atomically:encoding:)"
---

# write(to:atomically:encoding:)

Writes the contents of the receiver to the URL specified by url using the specified encoding.

## Declaration

```swift
func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
```

## Parameters

- `url`: The URL to which to write the receiver. Only file URLs are supported.
- `useAuxiliaryFile`: If doc://com.apple.documentation/documentation/Swift/true, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to url. If doc://com.apple.documentation/documentation/Swift/false, the receiver is written directly to url. The doc://com.apple.documentation/documentation/Swift/true option guarantees that url, if it exists at all, won’t be corrupted even if the system should crash during writing. The useAuxiliaryFile parameter is ignored if url is not of a type that can be accessed atomically.
- `enc`: The encoding to use for the output.

## Discussion

Discussion This method stores the specified encoding with the file in an extended attribute under the name com.apple.TextEncoding. The value contains the IANA name for the encoding and the CFStringEncoding value for the encoding, separated by a semicolon. The CFStringEncoding value is written as an ASCII string containing an unsigned 32-bit decimal integer and is not terminated by a null character. One or both of these values may be missing. Examples of the value written include the following: MACINTOSH;0 UTF-8;134217984 UTF-8; ;3071 The methods init(contentsOfFile:usedEncoding:), NSString/init(contentsOfURL:usedEncoding:)-2c72d, stringWithContentsOfFile:usedEncoding:error:, and NSString/init(contentsOfURL:usedEncoding:)-9jrum use this information to open the file using the right encoding. note: In the future this attribute may be extended compatibly by adding additional information after what’s there now, so any readers should be prepared for an arbitrarily long value for this attribute, with stuff following the CFStringEncoding value, separated by a non-digit. note: In Swift, this method returns Void and is marked with the throws keyword to indicate that it throws an error in cases of failure. You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language and About Imported Cocoa Error Parameters.

## See Also

### Writing to a File or URL

- [write(toFile:atomically:encoding:)](foundation/nsstring/write(tofile:atomically:encoding:).md)
