Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

macos - Writing a String to an NSOutputStream in Swift

I'm trying to write a String to an NSOutputStream in Swift. Writing Strings that way with Objective C usually works by passing it as NSData

NSData *data = [[NSData alloc] initWithData:[mystring dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];

This does not work with swift

var data: NSData = mystring.dataUsingEncoding(NSUTF8StringEncoding)!
outputStream.write(data, maxLength: data.length)

this yields the error

'NSData' is not convertible to 'UnsafePointer'

for the line that writes the data to the stream.

How would you write a String to an NSOutputStream in Swift?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In recent Swift it should be even easier and NSData is no longer needed.

let s = "String to encode"
let encodedDataArray = [UInt8](s.utf8)
outputstream.write(encodedDataArray, maxLength: encodedDataArray.count)

Arrays can be accessed as buffers of the correct their type (see withUnsafeBufferPointer). I think the array is necessary because the utf8 view is not actually instantiated as a full array but just a view into the original string.

In production code you should check the return value of the write to the output stream and depending on your scenario check there is space before the write but the focus of this answer is the encoding of the Swift String so that it can be written.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...