Reading Data into a Struct in Swift
Reading the entire structure from the data does not work because
the struct members are padded to their natural boundary. The
memory layout of struct XPLBeacon
is
A B x x C C C C D D D D
where
offset member
0 A - majorVersion (UInt8)
1 B - minorVersion (UInt8)
2 x x - padding
4 C C C C - applicationHostId (UInt32)
8 D D D D - versionNumber (UInt32)
and the padding is inserted so that the UInt32
members are
aligned to memory addresses which are a multiple of their size. This is
also confirmed by
print(MemoryLayout<XPLBeacon>.size) // 12
(For more information about alignment in Swift, see
Type Layout).
If you read the entire data into the struct then the bytes are assigned
as follows
01 02 0A 00 00 00 0B 00 00 00
A B x x C C C C D D D D
which explains why major/minorVersion
are correct, but applicationHostId
and versionNumber
are wrong. Reading all members separately from the data is the correct solution.
Access data of of struct swift
Text(response!.choices[2])
This line returns a Choice struct which is not a string representable. You need to go a level deeper and access it's text property.
Text(response!.choices[2].text)
I assume you have hardcoded and forced unwrapped for the example's sake. Otherwise follow safe coding practices :)
How to retrieve values from struct in swift
If you declare skillArray
as:
var skillArray = Array<Skill>()
then this should work:
print(each.name)
Swift 4 : how to write/load structure from file
- Make the type of your structure conform to Codable protocol
- Use PropertyListEncoder to encode and decode to property list
- Store that property list to the file system.
See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
Related Topics
No Such Module 'Restkit' With Cocoapods and Swift
Command Compileswiftsources Failed With a Nonzero Exit Code Xcode 10
How to Get User Home Directory Path (Users/"User Name") Without Knowing the Username in Swift3
Dispatchsourcetimer and Swift 3.0
Every Uialertcontroller Disappear Automatically Before User Responds - Since iOS 13
Error When Trying to Save Image in Nsuserdefaults Using Swift
Read-Only Properties of Protocols in Swift
Order of Modifiers in Swiftui View Impacts View Appearance
How to Access Program Arguments in Swift
Why Is the Shorthand Argument Name $0 Returning a Tuple of All Parameters
Compile Error in Swift 4 on Parameter Passing
How to Create Custom Notifications in Swift 3
Programmatically Navigate to New View in Swiftui
Hide/Show Tab Bar When Push/Back. Swift
How to Obtain the Selected Text from the Frontmost Application in MACos