Trikalabs
  • Home
  • Best online TDD videos
  • Book Suggestions
  • About Me
  • Contact
Trikalabs
No Result
View All Result

C Union equivalent in Swift

by fragi
May 24, 2023
in Uncategorized
Share on FacebookShare on Twitter

In C we can declare unions as follows:

C
1
2
3
4
union Data {
   int i;
   uint u;
} data;

So the same storage is used for the int and uint.

We can achieve something similar in Swift using bitPattern.

Swift
1
2
3
4
5
let a: Int8 = 1
let b = UInt8(bitPattern: a)
 
let negativeA: Int8 = -1
let bFromNegative = UInt8(bitPattern: negativeA)

In the above example b is 1 and bFromNegative is 255 (the two complement of -1).

UInt8(bitPattern: … initialiser will use the same bit storage.

fragi

fragi

Related Posts

Uncategorized

Equal arrays

May 24, 2023

In this short article we explore when two array are equal in Swift. Let's start we the obvious cases: ...

Uncategorized

Unit tests in playground

May 24, 2023

In this short article we will run unit tests on a Playground. Lets create a Playground and add the code...

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Advertise
  • Privacy & Policy
  • Contact

© 2019 Trikalabs Ltd. All rights reserved.

No Result
View All Result
  • Home
  • About Me
  • A curated list with the best free online TDD videos
  • Book Suggestions
  • Pinner Code Club

© 2019 Trikalabs Ltd. All rights reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.