You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4中使用CryptoSwift报错:表达式类型缺乏上下文导致歧义

Fixing "Type of expression is ambiguous without more context" in CryptoSwift AES Encryption (Swift 4)

The error you're hitting stems from a few mismatches between your code and how CryptoSwift expects AES parameters to be structured in Swift 4. Let's break down the issues and fix them step by step:

Key Issues in Your Code

  • String vs. Byte Array Mismatch: CryptoSwift's AES initializer requires key and IV as [UInt8] (byte arrays), not raw String values.
  • Incorrect Block Mode Syntax: The iv isn't a separate parameter for AES initialization—it's an associated value of the CBC block mode enum.
  • Unsafe Force Unwraps: Using ! on data and try! can cause crashes if operations fail. Since your function is marked throws, we should properly propagate errors instead.
  • Redundant Optional Unwrap: The encrypt() method returns a non-optional [UInt8] on success, so enc! is unnecessary.

Corrected Code

Here's the revised function that resolves all these problems:

func aesEncrypt(_ key: String, iv: String) throws -> String {
    guard let data = self.data(using: .utf8) else {
        throw NSError(domain: "EncryptionError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to convert string to UTF-8 data"])
    }
    
    let keyBytes = Array(key.utf8)
    let ivBytes = Array(iv.utf8)
    
    // Initialize AES with correct block mode syntax (IV is part of CBC)
    let aes = AES(key: keyBytes, blockMode: CBC(iv: ivBytes), padding: .pkcs7)
    let encryptedBytes = try aes.encrypt(Array(data))
    
    let encData = Data(encryptedBytes)
    return encData.base64EncodedString()
}

Important Additional Notes

  • Key/IV Length Requirements: Make sure your key is 16, 24, or 32 bytes long (for AES-128, AES-192, AES-256 respectively) and your IV is exactly 16 bytes. If your input strings don't match these lengths, you may need to pad or hash them first (e.g., using SHA-256 to derive a 32-byte key from a shorter string).
  • Error Handling: The guard statement now throws a meaningful error if string-to-data conversion fails, and we use try instead of try! to let encryption errors propagate to the caller for proper handling.
  • Version Compatibility: This code works with CryptoSwift versions compatible with Swift 4 (typically 0.8.x or 0.9.x). If you're using a newer version, syntax might shift slightly, but the core logic remains consistent.

内容的提问来源于stack exchange,提问作者Hitesh Mor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:33:24