Bird
0
0

Identify the mistake in this Swift code snippet intended to save a password to the Keychain:

medium📝 Debug Q6 of 15
iOS Swift - Local Data Persistence
Identify the mistake in this Swift code snippet intended to save a password to the Keychain:
let password = "securePass"
let data = password.data(using: .utf8)
let query: [String: Any] = [
  kSecClass as String: kSecClassGenericPassword,
  kSecAttrAccount as String: "user",
  kSecValueData as String: data as Any
]
let status = SecItemAdd(query as CFDictionary, nil)
AkSecAttrAccount should be kSecAttrService.
BThe data is not unwrapped before being added to the query dictionary.
CSecItemAdd requires a completion handler.
DkSecClassGenericPassword is not a valid keychain class.
Step-by-Step Solution
Solution:
  1. Step 1: Check Data Conversion

    password.data(using: .utf8) returns an optional Data?.
  2. Step 2: Inspect Query Dictionary

    The code uses 'data as Any' without unwrapping, so if data is nil, it inserts nil which is invalid.
  3. Step 3: Correct Usage

    Data should be safely unwrapped before adding to the query dictionary.
  4. Final Answer:

    The data is not unwrapped before being added to the query dictionary. -> Option B
  5. Quick Check:

    Always unwrap optional Data before use [OK]
Quick Trick: Unwrap optional Data before adding to Keychain query [OK]
Common Mistakes:
  • Passing optional Data directly without unwrapping
  • Confusing kSecAttrAccount with kSecAttrService
  • Expecting SecItemAdd to have a completion handler

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes