Access a struct property by its name as a string in Swift - struct

Let's say I have the following struct in Swift:
struct Data {
let old: Double
let new: Double
}
Now I have a class with an array of Data structs:
class MyClass {
var myDataArray: [Data]
}
Now let's say I want to calculate the average of either the old or the new values:
func calculateAverage(oldOrNew: String) -> Double {
var total = 0.0
count = 0
for data in myDataArray {
total += data.oldOrNew
count++
}
return total / Double(count)
}
And then:
let oldAverage = calculateAverage("old")
let newAverage = calculateAverage("new")
But this obviously doesn't work, since oldOrNew is not a member of my struct.
How can I access old or new from "old" or "new" ?

What about this "reflection-less" solution?
struct Data {
let old: Double
let new: Double
func valueByPropertyName(name:String) -> Double {
switch name {
case "old": return old
case "new": return new
default: fatalError("Wrong property name")
}
}
}
Now you can do this
let data = Data(old: 0, new: 1)
data.valueByPropertyName("old") // 0
data.valueByPropertyName("new") // 1

You're looking for key-value-coding (KVC) that is accessing properties by key (path).
Short answer: A struct does not support KVC.
If the struct is not mandatory in your design use a subclass of NSObject there you get KVC and even operators like #avg for free.
class MyData : NSObject {
#objc let old, new: Double
init(old:Double, new:Double) {
self.old = old
self.new = new
}
}
let myDataArray : NSArray = [MyData(old: 1, new: 3), MyData(old:5, new: 9), MyData(old: 12, new: 66)]
let averageOld = myDataArray.value(forKeyPath:"#avg.old")
let averageNew = myDataArray.value(forKeyPath: "#avg.new")
Edit: In Swift 4 a struct does support Swift KVC but the operator #avg is not available

You wouldn't access a struct property by name in Swift any more than you would in C++. You'd provide a block.
Extemporaneous:
func calculateAverage(getter: (Data) -> Double) {
... total += getter(data) ...
}
...
calculateAverage({$0.old})
calculateAverage({$0.new})
Possibly with average {$0.old} being a more natural syntax — the verb isn't really helpful and if you're asserting what it is, not what the computer should do, then omitting the brackets looks fine.

Related

SwiftUI String display character after character

i need a hint cause i don‘t know how to start.
I want to display a string char after char with a short delay but I’m not sure how to do it.
Should i convert the string into an array and display this array in a ForEach or is it possible to do this with string manipulation?
Thanks for every hint :-)
Michael
Here's an example where you can input a String. It will turn it into an array of Strings (for each character), add them onto the screen using an HStack and Text objects. Each Text has initial .opacity of 0.0 and then a function is called that will loop through each Text, turning the .opacity to 1.0.
struct CharView: View {
var characterArray: [String]
#State var characterLoopIndex: Int = -1
let loopDuration: Double = 0.5
init(input: String) {
characterArray = input.map { String($0) }
}
var body: some View {
HStack(spacing: 0) {
ForEach(characterArray.indices) { index in
Text("\(characterArray[index])")
.opacity(characterLoopIndex >= index ? 1 : 0)
.animation(.linear(duration: loopDuration))
}
}
.onAppear(perform: {
startCharacterAnimation()
})
}
func startCharacterAnimation() {
let timer = Timer.scheduledTimer(withTimeInterval: loopDuration, repeats: true) { (timer) in
characterLoopIndex += 1
if characterLoopIndex >= characterArray.count {
timer.invalidate()
}
}
timer.fire()
}
}
Usage:
CharView(input: "This is a test string")

SwiftUI reorder CoreData Objects in List

I want to change the order of the rows in a list that retrieves objects from the core data. Moving rows works, but the problem is that I can't save the changes. I don't know how to save the changed Index of the CoreData Object.
Here is my Code:
Core Data Class:
public class CoreItem: NSManagedObject, Identifiable{
#NSManaged public var name: String
}
extension CoreItem{
static func getAllCoreItems() -> NSFetchRequest <CoreItem> {
let request: NSFetchRequest<CoreItem> = CoreItem.fetchRequest() as! NSFetchRequest<CoreItem>
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
request.sortDescriptors = [sortDescriptor]
return request
}
}
extension Collection where Element == CoreItem, Index == Int {
func move(set: IndexSet, to: Int, from managedObjectContext: NSManagedObjectContext) {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
List:
struct CoreItemList: View {
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(fetchRequest: CoreItem.getAllCoreItems()) var CoreItems: FetchedResults<CoreItem>
var body: some View {
NavigationView{
List {
ForEach(CoreItems, id: \.self){
coreItem in
CoreItemRow(coreItem: coreItem)
}.onDelete {
IndexSet in let deleteItem = self.CoreItems[IndexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
}
.onMove {
self.CoreItems.move(set: $0, to: $1, from: self.managedObjectContext)
}
}
.navigationBarItems(trailing: EditButton())
}.navigationViewStyle(StackNavigationViewStyle())
}
}
Thank you for help.
Caveat: the answer below is untested, although I used parallel logic in a sample project and that project seems to be working.
There's a couple parts to the answer. As Joakim Danielson says, in order to persist the user's preferred order you will need to save the order in your CoreItem class. The revised class would look like:
public class CoreItem: NSManagedObject, Identifiable{
#NSManaged public var name: String
#NSManaged public var userOrder: Int16
}
The second part is to keep the items sorted based on the userOrder attribute. On initialization the userOrder would typically default to zero so it might be useful to also sort by name within userOrder. Assuming you want to do this, then in CoreItemList code:
#FetchRequest( entity: CoreItem.entity(),
sortDescriptors:
[
NSSortDescriptor(
keyPath: \CoreItem.userOrder,
ascending: true),
NSSortDescriptor(
keyPath:\CoreItem.name,
ascending: true )
]
) var coreItems: FetchedResults<CoreItem>
The third part is that you need to tell swiftui to permit the user to revise the order of the list. As you show in your example, this is done with the onMove modifier. In that modifier you perform the actions needed to re-order the list in the user's preferred sequence. For example, you could call a convenience function called move so the modifier would read:
.onMove( perform: move )
Your move function will be passed an IndexSet and an Int. The index set contains all the items in the FetchRequestResult that are to be moved (typically that is just one item). The Int indicates the position to which they should be moved. The logic would be:
private func move( from source: IndexSet, to destination: Int)
{
// Make an array of items from fetched results
var revisedItems: [ CoreItem ] = coreItems.map{ $0 }
// change the order of the items in the array
revisedItems.move(fromOffsets: source, toOffset: destination )
// update the userOrder attribute in revisedItems to
// persist the new order. This is done in reverse order
// to minimize changes to the indices.
for reverseIndex in stride( from: revisedItems.count - 1,
through: 0,
by: -1 )
{
revisedItems[ reverseIndex ].userOrder =
Int16( reverseIndex )
}
}
Technical reminder: the items stored in revisedItems are classes (i.e., by reference), so updating these items will necessarily update the items in the fetched results. The #FetchedResults wrapper will cause your user interface to reflect the new order.
Admittedly, I'm new to SwiftUI. There is likely to be a more elegant solution!
Paul Hudson (Hacking With Swift) has quite a bit more detail. Here is a link for info on moving data in a list. Here is a link for using core data with SwiftUI (it involves deleting items in a list, but is closely analogous to the onMove logic)
Below you can find a more generic approach to this problem. The algorithm minimises the number of CoreData entities that require an update, to the contrary of the accepted answer. My solution is inspired by the following article: https://www.appsdissected.com/order-core-data-entities-maximum-speed/
First I declare a protocol as follows to use with your model struct (or class):
protocol Sortable {
var sortOrder: Int { get set }
}
As an example, assume we have a SortItem model which implements our Sortable protocol, defined as:
struct SortItem: Identifiable, Sortable {
var id = UUID()
var title = ""
var sortOrder = 0
}
We also have a simple SwiftUI View with a related ViewModel defined as (stripped down version):
struct ItemsView: View {
#ObservedObject private(set) var viewModel: ViewModel
var body: some View {
NavigationView {
List {
ForEach(viewModel.items) { item in
Text(item.title)
}
.onMove(perform: viewModel.move(from:to:))
}
}
.navigationBarItems(trailing: EditButton())
}
}
extension ItemsView {
class ViewModel: ObservableObject {
#Published var items = [SortItem]()
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
// Note: Code that updates CoreData goes here, see below
}
}
}
Before I continue to the algorithm, I want to note that the destination variable from the move function does not contain the new index when moving items down the list. Assuming that only a single item is moved, retrieving the new index (after the move is complete) can be achieved as follows:
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
if let oldIndex = source.first, oldIndex != destination {
let newIndex = oldIndex < destination ? destination - 1 : destination
// Note: Code that updates CoreData goes here, see below
}
}
The algorithm itself is implemented as an extension to Array for the case that the Element is of the Sortable type. It consists of a recursive updateSortOrder function as well as a private helper function enclosingIndices which retrieves the indices that enclose around a certain index of the array, whilst remaining within the array bounds. The complete algorithm is as follows (explained below):
extension Array where Element: Sortable {
func updateSortOrder(around index: Int, for keyPath: WritableKeyPath<Element, Int> = \.sortOrder, spacing: Int = 32, offset: Int = 1, _ operation: #escaping (Int, Int) -> Void) {
if let enclosingIndices = enclosingIndices(around: index, offset: offset) {
if let leftIndex = enclosingIndices.first(where: { $0 != index }),
let rightIndex = enclosingIndices.last(where: { $0 != index }) {
let left = self[leftIndex][keyPath: keyPath]
let right = self[rightIndex][keyPath: keyPath]
if left != right && (right - left) % (offset * 2) == 0 {
let spacing = (right - left) / (offset * 2)
var sortOrder = left
for index in enclosingIndices.indices {
if self[index][keyPath: keyPath] != sortOrder {
operation(index, sortOrder)
}
sortOrder += spacing
}
} else {
updateSortOrder(around: index, for: keyPath, spacing: spacing, offset: offset + 1, operation)
}
}
} else {
for index in self.indices {
let sortOrder = index * spacing
if self[index][keyPath: keyPath] != sortOrder {
operation(index, sortOrder)
}
}
}
}
private func enclosingIndices(around index: Int, offset: Int) -> Range<Int>? {
guard self.count - 1 >= offset * 2 else { return nil }
var leftIndex = index - offset
var rightIndex = index + offset
while leftIndex < startIndex {
leftIndex += 1
rightIndex += 1
}
while rightIndex > endIndex - 1 {
leftIndex -= 1
rightIndex -= 1
}
return Range(leftIndex...rightIndex)
}
}
First, the enclosingIndices function. It returns an optional Range<Int>. The offset argument defines the distance for the enclosing indices left and right of the index argument. The guard ensures that the complete enclosing indices are contained within the array. Further, in case the offset goes beyond the startIndex or endIndex of the array, the enclosing indices will be shifted to the right or left, respectively. Hence, at the boundaries of the array, the index is not necessarily located in the middle of the enclosing indices.
Second, the updateSortOrder function. It requires at least the index around which the update of the sorting order should be started. This is the new index from the move function in the ViewModel. Further, the updateSortOrder expects an #escaping closure providing two integers, which will be explained below. All other arguments are optional. The keyPath is defaulted to \.sortOrder in conformance with the expectations from the protocol. However, it can be specified if the model parameter for sorting differs. The spacing argument defines the sort order spacing that is typically used. The larger this value, the more sort operations can be performed without requiring any other CoreData update except for the moved item. The offset argument should not really be touched and is used in the recursion of the function.
The function first requests the enclosingIndices. In case these are not found, which happens immediately when the array is smaller than three items or either inside one of the recursions of the updateSortOrder function when the offset is such that it would go beyond the boundaries of the array; then the sort order of all items in the array are reset in the else case. In that case, if the sortOrder differs from the items existing value, the #escaping closure is called. It's implementation will be discussed further below.
When the enclosingIndices are found, both the left and right index of the enclosing indices not being the index of the moved item are determined. With these indices known, the existing 'sort order' values for these indices are obtained through the keyPath. It is then verified if these values are not equal (which could occur if the items were added with equal sort orders in the array) as well as if a division of the difference between the sort orders and the number of enclosing indices minus the moved item would result in a non-integer value. This basically checks whether there is a place left for the moved item's potentially new sort order value within the minimum spacing of 1. If this is not the case, the enclosing indices should be expanded to the next higher offset and the algorithm run again, hence the recursive call to updateSortOrder in that case.
When all was successful, the new spacing should be determined for the items between the enclosing indices. Then all enclosing indices are looped through and each item's sorting order is compared to the potentially new sorting order. In case it changed, the #escaping closure is called. For the next item in the loop the sort order value is updated again.
This algorithm results in the minimum amount of callbacks to the #escaping closure. Since this only happens when an item's sort order really needs to be updated.
Finally, as you perhaps guessed, the actual callbacks to CoreData will be handled in the closure. With the algorithm defined, the ViewModel move function is then updated as follows:
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
if let oldIndex = source.first, oldIndex != destination {
let newIndex = oldIndex < destination ? destination - 1 : destination
items.updateSortOrder(around: newIndex) { [weak self] (index, sortOrder) in
guard let self = self else { return }
var item = self.items[index]
item.sortOrder = sortOrder
// Note: Callback to interactor / service that updates CoreData goes here
}
}
}
Please let me know if you have any questions regarding this approach. I hope you like it.
Had a problem with Int16 and solved it by changing it to #NSManaged public var userOrder: NSNumber? and in the func: NSNumber(value: Int16( reverseIndex ))
As well I needed to add try? managedObjectContext.save() in the func to actually save the new order.
Now its working fine - thanks!
I'm not sure using a CoreData NSManagedObject for a view model object is the best approach, but if you do below is a sample for moving items in a SwiftUI List and persisting an object value based sort order.
An UndoManager is used in the event an error occurs during the move to rollback any changes.
class Note: NSManagedObject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
return NSFetchRequest<Note>(entityName: "Note")
}
#NSManaged public var id: UUID?
#NSManaged public var orderIndex: Int64
#NSManaged public var text: String?
}
struct ContentView: View {
#Environment(\.editMode) var editMode
#Environment(\.managedObjectContext) var viewContext
#FetchRequest(sortDescriptors:
[NSSortDescriptor(key: "orderIndex", ascending: true)],
animation: .default)
private var notes: FetchedResults<Note>
var body: some View {
NavigationView {
List {
ForEach (notes) { note in
Text(note.text ?? "")
}
}
.onMove(perform: moveNotes)
}
.navigationTitle("Notes")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
}
}
func moveNotes(_ indexes: IndexSet, _ i: Int) {
guard
1 == indexes.count,
let from = indexes.first,
from != i
else { return }
var undo = viewContext.undoManager
var resetUndo = false
if undo == nil {
viewContext.undoManager = .init()
undo = viewContext.undoManager
resetUndo = true
}
defer {
if resetUndo {
viewContext.undoManager = nil
}
}
do {
try viewContext.performAndWait {
undo?.beginUndoGrouping()
let moving = notes[from]
if from > i { // moving up
notes[i..<from].forEach {
$0.orderIndex = $0.orderIndex + 1
}
moving.orderIndex = Int64(i)
}
if from < i { // moving down
notes[(from+1)..<i].forEach {
$0.orderIndex = $0.orderIndex - 1
}
moving.orderIndex = Int64(i)
}
undo?.endUndoGrouping()
try viewContext.save()
}
} catch {
undo?.endUndoGrouping()
viewContext.undo()
// TODO: something with the error
// set a state variable to display the error condition
fatalError(error.localizedDescription)
}
}
}
if do like this
.onMove {
self.CoreItems.move(set: $0, to: $1, from: self.managedObjectContext)
try? managedObjectContext.save()

Access String value in enum without using rawValue

I would like to replace my global string constants with a nested enum for the keys I'm using to access columns in a database.
The structure is as follows:
enum DatabaseKeys {
enum User: String {
case Table = "User"
case Username = "username"
...
}
...
}
Each table in the database is an inner enum, with the name of the table being the enum's title. The first case in each enum will be the name of the table, and the following cases are the columns in its table.
To use this, it's pretty simple:
myUser[DatabaseKeys.User.Username.rawValue] = "Johnny"
But I will be using these enums a lot. Having to append .rawValue to every instance will be a pain, and it's not as readable as I'd like it to be. How can I access the String value without having to use rawValue? It'd be great if I can do this:
myUser[DatabaseKeys.User.Username] = "Johnny"
Note that I'm using Swift 2. If there's an even better way to accomplish this I'd love to hear it!
While I didn't find a way to do this using the desired syntax with enums, this is possible using structs.
struct DatabaseKeys {
struct User {
static let identifier = "User"
static let Username = "username"
}
}
To use:
myUser[DatabaseKeys.User.Username] = "Johnny"
Apple uses structs like this for storyboard and row type identifiers in the WatchKit templates.
You can use CustomStringConvertible protocol for this.
From documentation,
String(instance) will work for an instance of any type, returning its
description if the instance happens to be CustomStringConvertible.
Using CustomStringConvertible as a generic constraint, or accessing a
conforming type's description directly, is therefore discouraged.
So, if you conform to this protocol and return your rawValue through the description method, you will be able to use String(Table.User) to get the value.
enum User: String, CustomStringConvertible {
case Table = "User"
case Username = "username"
var description: String {
return self.rawValue
}
}
var myUser = [String: String]()
myUser[String(DatabaseKeys.User.Username)] = "Johnny"
print(myUser) // ["username": "Johnny"]
You can use callAsFunction (New in Swift 5.2) on your enum that conforms to String.
enum KeychainKey: String {
case userId
case email
}
func callAsFunction() -> String {
return self.rawValue
}
usage:
KeychainKey.userId()
You can do this with custom class:
enum Names: String {
case something, thing
}
class CustomData {
subscript(key: Names) -> Any? {
get {
return self.customData[key.rawValue]
}
set(newValue) {
self.customData[key.rawValue] = newValue
}
}
private var customData = [String: Any]()
}
...
let cData = CustomData()
cData[Names.thing] = 56
Edit:
I found an another solution, that working with Swift 3:
enum CustomKey: String {
case one, two, three
}
extension Dictionary where Key: ExpressibleByStringLiteral {
subscript(key: CustomKey) -> Value? {
get {
return self[key.rawValue as! Key]
}
set {
self[key.rawValue as! Key] = newValue
}
}
}
var dict: [String: Any] = [:]
dict[CustomKey.one] = 1
dict["two"] = true
dict[.three] = 3
print(dict["one"]!)
print(dict[CustomKey.two]!)
print(dict[.three]!)
If you are able to use User as dictionary key instead of String (User is Hashable by default) it would be a solution.
If not you should use yours with a nested struct and static variables/constants.

Convert an String to an array of int8

I have an C struct (old library, blah blah blah) which contains an C string, now I need to convert CFString and Swift strings into this c string. Something like
struct Product{
char name[50];
char code[20];
}
So I'm trying to assign it as
productName.getCString(&myVarOfStructProduct.name, maxLength: 50, encoding: NSUTF8StringEncoding)
but the compiler is giving me the following error: cannot convert type (int8, int8, int8....) to [CChar].
A possible solution:
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
strlcpy(UnsafeMutablePointer($0), productName, UInt(sizeofValue(myVarOfStructProduct.name)))
}
Inside the block, $0 is a (mutable) pointer to the tuple. This pointer is
converted to an UnsafeMutablePointer<Int8> as expected by the
BSD library function strlcpy().
It also uses the fact that the Swift string productName is automatically
to UnsafePointer<UInt8>
as explained in String value to UnsafePointer<UInt8> function parameter behavior. As mentioned in the comments in that
thread, this is done by creating a temporary UInt8 array (or sequence?).
So alternatively you could enumerate the UTF-8 bytes explicitly and put them
into the destination:
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
tuplePtr -> Void in
var uint8Ptr = UnsafeMutablePointer<UInt8>(tuplePtr)
let size = sizeofValue(myVarOfStructProduct.name)
var idx = 0
if size == 0 { return } // C array has zero length.
for u in productName.utf8 {
if idx == size - 1 { break }
uint8Ptr[idx++] = u
}
uint8Ptr[idx] = 0 // NUL-terminate the C string in the array.
}
Yet another possible solution (with an intermediate NSData object):
withUnsafeMutablePointer(&myVarOfStructProduct.name) {
tuplePtr -> Void in
let tmp = productName + String(UnicodeScalar(0)) // Add NUL-termination
let data = tmp.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
data.getBytes(tuplePtr, length: sizeofValue(myVarOfStructProduct.name))
}
Update for Swift 3:
withUnsafeMutablePointer(to: &myVarOfStructProduct.name) {
$0.withMemoryRebound(to: Int8.self, capacity: MemoryLayout.size(ofValue: myVarOfStructProduct.name)) {
_ = strlcpy($0, productName, MemoryLayout.size(ofValue: myVarOfStructProduct.name))
}
}

swift How to use enum as parameter in constructing struct?

I was doing an experiment of Swift programming book and stuck with construct a struct inner the struct itself. But the error reported the parameter is unwrapped. How could I take it value as parameter?
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
func FullDeck() -> Card[] {
var deck: Card[]
for i in 1...13
{
for j in 0...3
{
let rank_para = Rank.fromRaw(i)
let suit_para = Suit.fromRaw(j)
**deck.append(Card(rank: rank_para, suit : suit_para ))
//value of optional type unwrapped;did you mean to use ? or !**
}
}
return deck
}
}
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.toRaw())
}
}
func compare(sec:Rank) -> Bool {
var first = 0
var second = 0
if self.toRaw() == 1 {
first = 1
} else {
first = self.toRaw()
}
if sec.toRaw() == 1 {
second = 1
} else {
second = self.toRaw()
}
return first > second
}
}
enum Suit: Int{
case Spades = 0
case Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
the fromRaw method returns an optional value: Rank? and Suit?. That means that the value could be nil. You need to check for that:
if let aRank = rank_para {
if let aSuit = suit_para {
deck.append(Card(rank: aRank, suit: aSuit))
}
}
By using "if let", you "unwrap" the optional value into a value (aRank and aSuit) that is no longer optional (cannot be nil).
Another way to do that:
if rank_para and suit_para {
deck.append(Card(rank: rank_para!, suit: suit_para!))
}
Here, you are checking if rank_para and suit_para are nil. If they both are not, you call append and "unwrap" the optional values using !. ! means if the value is nil throw a runtime error, otherwise, treat this variable as if it cannot be nil.

Resources