[swift-users] Simple text file I/O with Swift 3

Quinn "The Eskimo!" eskimo1 at apple.com
Mon May 30 03:11:41 CDT 2016

On 28 May 2016, at 19:05, Ken Burgett via swift-users <swift-users at swift.org> wrote:

> print(buf)

The trick here is to replace the above line with:

    print(String(validatingUTF8: buf))

`fgets` sets up `buf` to hold a C string, so you have to convert it to a Swift string.  How do you do this depends on the encoding of the bytes.  If you expect the C string to be UTF-8, then `String(validatingUTF8:)` is the way to go.

IMPORTANT: This conversion can fail, which is why the above will print a bunch of optional strings, and you will have to decide what to your program should do when it does.

                   *                   *                   *

btw This question came up recently.  See the thread for other suggestions about how to handle it.


Share and Enjoy
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

More information about the swift-users mailing list