---
title: "init(contentsOfFile:usedEncoding:)"
framework: foundation
role: symbol
role_heading: Initializer
path: "foundation/nsstring/init(contentsoffile:usedencoding:)"
---

# init(contentsOfFile:usedEncoding:)

Returns an NSString object initialized by reading data from the file at a given path and returns by reference the encoding used to interpret the characters.

## Declaration

```swift
convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws
```

## Parameters

- `path`: A path to a file.
- `enc`: Upon return, if the file is read successfully, contains the encoding used to interpret the file at path. For possible values, see doc://com.apple.foundation/documentation/Foundation/NSStringEncoding.

## Return Value

Return Value An NSString object initialized by reading data from the file named by path. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returns nil.

## Discussion

Discussion note: In Swift, this method returns a nonoptional result 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

### Creating and Initializing a String from a File

- [init(contentsOfFile:encoding:)](foundation/nsstring/init(contentsoffile:encoding:).md)
