Writing a String to an NSOutputStream in Swift

后端 未结 3 1780
抹茶落季
抹茶落季 2020-12-03 08:38

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

<
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 09:11

    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.

提交回复
热议问题