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

# init(contentsOfFile:encoding:)

Returns an NSString object initialized by reading data from the file at a given path using a given encoding.

## Declaration

```swift
convenience init(contentsOfFile path: String, encoding enc: UInt) throws
```

## Parameters

- `path`: A path to a file.
- `enc`: The encoding of 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 using the encoding, enc. 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:usedEncoding:)](foundation/nsstring/init(contentsoffile:usedencoding:).md)
