代码之家  ›  专栏  ›  技术社区  ›  Oleg Gordiichuk

在Swift中,函数返回两种以上的类型是一种最佳方式吗?

  •  1
  • Oleg Gordiichuk  · 技术社区  · 6 年前

    字符串 数据 以后可能会扩展到其他类型。

    我开始寻找建议,发现这可以通过 多元组

    我决定继续 枚举类型 .

    enum SecureRandomInput {
        case forString
        case forData
    }
    
    
    enum SecureRandomOutput {
        case forString(String)
        case forData(Data)
    
        static func generate(with type: SecureRandomInput, bytesCount: Int) -> SecureRandomOutput {
            var randomBytes = [UInt8](repeating: 0, count: bytesCount)
            let _ = SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes)
            switch type {
            case .forString:
                return SecureRandomOutput.forString(randomBytes.map({ String(format: "%02hhx", $0) }).joined(separator: ""))
            case .forData:
                return SecureRandomOutput.forData(Data(bytes: randomBytes, count: bytesCount))
            }
        }
    }
    

    所以问题是:

    1) 在特定情况下使用枚举比使用元组更灵活?

    3) 在Swift 4中,我们还有其他方法可以实现所需的行为吗?(不带枚举和元组)

    2 回复  |  直到 6 年前
        1
  •  1
  •   pacification    6 年前
    1. 我同意你的看法,枚举是分离不同行为的更清晰的方法,而不是创建大量元组。

    2. 代码是相当标准的。

    3. SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes) 差不多)。现在这是好的,但是将来它可以成为重构代码的一个选项。

        2
  •  1
  •   Joakim Danielson    6 年前

    另一种方法是使用闭包和泛型

    func generate<T>(bytesCount: Int, convert: ([UInt8]) ->T ) -> T {
        var randomBytes = [UInt8](repeating: 0, count: bytesCount)
        let _ = SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomBytes)
        return convert(randomBytes)
    }
    
    let x = generate(bytesCount: 7) {
        return Data(bytes: $0, count: $0.count)
    }
    
    let y = generate(bytesCount: 7) { bytes in
        return bytes.map({ String.init(format: "%02hhx", $0) }).joined(separator: "")
    }