简体   繁体   English

如何在 Swift 结构中正确调用我的 init function?

[英]How do I properly call my init function in a Swift Struct?

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.我当前的代码旨在为加密钱包密钥制作 Sha-256 hash,然后将其打印给我,以便我确认它是否正常工作。 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.问题是 init function 似乎从未被调用过,所以我没有在控制台上打印任何内容。 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.编辑:我应该补充一点,如果我尝试在 init 之外使用 for 循环,我只会得到一个“预期声明”错误。 I did some research and I thought that init was what I was supposed to use in a situation like this.我做了一些研究,我认为 init 是我应该在这种情况下使用的。

Any help would be greatly appreciated!任何帮助将不胜感激!

As alluded to in the comments, @State is only for use within a SwiftUI View .正如评论中提到的,@State 仅适用于@State View中。

There are a couple of other minor errors, like leaving out "e" in your array.还有一些其他的小错误,比如在数组中遗漏了"e"

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:这是另一个本质上有点 Swift 风格的迭代:

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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM