[swift-users] withUnsafeMutableBytes is killing me

Ole Begemann ole at oleb.net
Tue Apr 25 04:58:54 CDT 2017


The withUnsafeMutableBytes method has two generic parameters, ResultType 
and ContentType:

|mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: 
(UnsafeMutablePointer 
<dash-apple-api://load?request_key=hsAKsXE560&language=swift><ContentType>) 
throws -> ResultType) rethrows -> ResultType|


In your examples, the type checker can't infer the type of ResultType. 
You'll have to state it explicitly by specifying the type of the 
closure's argument. For example:

msg.withUnsafeMutableBytes {
     (inPointer*: UnsafeMutablePointer<UInt8>*) -> Void in
     // ...
}


On 25.04.2017 10:45, Rick Mann via swift-users wrote:
> The following playground reproduces an issue I'm having, in that the code won't compile depending on the content of the closure. In fact, an empty closure is fine, but when I try to call certain things, it's not.
>
> I figure it has something to do with the type inference for inPointer, but I can't figure out what it needs to work.
>
> ---------------------------
> import Foundation
>
> //	OKAY:
>
> var msg = Data(capacity: 123456)
> msg.withUnsafeMutableBytes
> { (inPointer) -> Void in
> 	foo(inPointer)
> }
>
> //error: cannot convert value of type '(_) -> Void' to expected argument type '(UnsafeMutablePointer<_>) -> _'
> //{ (inPointer) -> Void in
> //^~~~~~~~~~~~~~~~~~~~~~~~
>
> msg.withUnsafeMutableBytes
> { (inPointer) -> Void in
> }
>
> //error: cannot convert value of type '(_) -> Void' to expected argument type '(UnsafeMutablePointer<_>) -> _'
> //{ (inPointer) -> Void in
> //^~~~~~~~~~~~~~~~~~~~~~~~
>
> msg.withUnsafeMutableBytes
> { (inPointer) -> Void in
> 	var s: Int
> 	lgs_error(inPointer, 123456, &s)
> }
>
> func
> foo(_ data: UnsafeMutableRawPointer!)
> {
> }
>
> func
> lgs_error(_ message: UnsafeMutablePointer<Int8>!,
> 	    _ message_capacity: Int,
> 	    _ message_size: UnsafeMutablePointer<Int>!) -> Int
> {
> }
> ---------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170425/ae9c25f6/attachment.html>


More information about the swift-users mailing list