Home > Software design >  How do I properly call my init function in a Swift Struct?
How do I properly call my init function in a Swift Struct?

Time:04-19

My current code is designed to make a Sha-256 hash for a crypto wallet key, and then print it to me so that I can confirm that it worked properly. Here's my code. By the way, I am a beginner, I still have much to learn.

import Foundation
import SwiftUI

struct dataManager {
    let characterArray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","f"]
      @State private var privKey = "0x"
    
        init() {
            for _ in 1...64 {
            privKey  = characterArray[Int(arc4random_uniform(16))]
        
            print(privKey)
        }
        
    }

}

The issue is the fact that the init function never seems to be called, so I don't get anything printed to the console. I tried dividing by zero to see if there was a crash, and there wasn't one, which leads me to believe that it wasn't called or something along those lines.

EDIT: I should add that if I try to use the for loop outside of init, I just get an "expected declaration" error. I did some research and I thought that init was what I was supposed to use in a situation like this.

Any help would be greatly appreciated!

CodePudding user response:

As alluded to in the comments, @State is only for use within a SwiftUI View.

There are a couple of other minor errors, like leaving out "e" in your array.

Here's a working version of your code, modified as little as possible:

struct DataManager {
    let characterArray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    var privKey = "0x"
    
    init() {
        for _ in 1...64 {
            privKey  = characterArray[Int(arc4random_uniform(16))]
            print(privKey)
        }
    }
}

let manager = DataManager()
print(manager.privKey)

Note that you could further refactor this. Here's another iteration that is a little Swift-ier in nature:

struct DataManager {
    let characterArray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    var privKey = "0x"
    
    init() {
        privKey  = (1...64).map { _ in characterArray.randomElement()! }.joined()
    }
}

Or:

struct DataManager {
    var privKey = "0x"   (1...64).map { _ in ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].randomElement()! }.joined()
}
  • Related