[swift-users] proper syntax for inout array handling?

Saagar Jha saagarjha28 at gmail.com
Thu Jun 9 21:21:56 CDT 2016


Swift handling of Arrays isn’t like C (for which you can use UnsafePointer)-you
don’t access the pointer of the third element. Instead, you can use Array
slices, which makes it a one liner:

destination[destinationStartIndex..<destinationStartIndex + count] =
source[sourceStartIndex..<sourceStartIndex + count]

In your case,

destination[0..<0 + 32] = source[0..<0 + 32]
destination[3..3 + 13] = source[0..<0 + 13]

As a function:

func memcpy(source: [UInt8], destination: inout [UInt8],
sourceStartIndex: Int = 0, destinationStartIndex: Int = 0, count: Int)
{
    destination[destinationStartIndex..<destinationStartIndex + count]
= source[sourceStartIndex..<sourceStartIndex + count]
}

memcpy(source: source, destination: &destination, count: 32)

memcpy(source: source, destination: &destination,
destinationStartIndex: 3, count: 13)



On Thu, Jun 9, 2016 at 1:38 PM Ken Burgett via swift-users <
swift-users at swift.org> wrote:

> I am converting a very dirty C program to Swift3, and their is plenty of
> pointer arithmetic to be dealt with.  As part of the effort, I have
> created a 'memcpy clone to help with some of the transformation.
> Here is the output from the REPL:
> ================================
>    1. var source = [UInt8](repeating: 0x1f, count: 32)
>    2. var destination = [UInt8](repeating: 0, count: 64)
>    3.
>    4. func memcpy(dest: inout [UInt8], src: inout [UInt8], count: Int)
>    5. {
>    6.   for ix in 0...count-1
>    7.   {
>    8.     dest[ix] = src[ix]
>    9.   }
>   10. }
>   11.
>   12. memcpy(dest: &destination, src: &source, count: 32 )
>   13.
>   14. memcpy(dest: &destination[3], src: &source, count: 13)
> error: repl.swift:14:26: error: cannot convert value of type 'UInt8' to
> expected argument type '[UInt8]'
> memcpy(dest: &destination[3], src: &source, count: 13)
> ==================================
> which shows me that the compiler does not like the form of
> &destination[13], and doesn't treat it as a [UInt8].
>
> What is the correct syntax for using a base + offset as a source or
> destination for a memory copy?
>
>
> --
> Ken Burgett
> Principal Software Engineer
> Email: kenb at iotone.io
> Office: 530.693.4449
> Mobile: 831.332.6846
> URL: www.iotone.co
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-- 
-Saagar Jha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160610/5826f61b/attachment.html>


More information about the swift-users mailing list