In: Computer Science
Swift Code 4 only please
var arr: [String] = ["a","b","s","c"]
var dictionary : [String : Int] = ["a":1, "b":2, "c":3, "d":4]
for i in arr
if(dict[i] = even)
print ("even number"
if else (dict[i] =odd)
print("odd number")
else
print("Does not exist")
Is there a way to compare the string array with the dictionary keys. Use the array to see if string exists as a key in the dictionary. Depending on the value of the key, it will print a specific code
In case of any query, do comment. Please rate answer. Thanks
Code:
//given array
var arr: [String] = ["a","b","s","c"]
//given dictionary
var dictionary : [String : Int] = ["a":1, "b":2, "c":3, "d":4]
//For loop to iterate over array
for i in arr
{
//condition to check whether array element exist in dictionary as a
key. dictionary.keys gives a collection of keys
//based on key present or not, decide the code to print in
corresponding if-else
if(dictionary.keys.contains(i)){
//! used to unwrap optional returned from dictionary values
if dictionary[i]! % 2 == 0
{
print("even number")
}
else
{
print("odd number")
}
}
else {
print("does not exist")
}
}
screen shot of code and output:
main.swift 1 1/given array 2 var arr: [String] = ["a", "b","s","c"] 4 //given dictionary 5 var dictionary : [String : Int] = ["a":1, "b":2, "-":3, "d":4] 7 8 9- //For Loop to iterate over array for i in arr { //condition to check whether array element exist in dictionary as a key. dictionary.keys gives a collection of keys //based on key present or not, decide the code to print in corresponding if-else if(dictionary.keys.contains(i)){ print("key \(i) exist in the dictionary.") 16 17 18 else { print("key \(i) does not exist in the dictionary.") } } input key a exist in the dictionary. key b exist in the dictionary. key s does not exist in the dictionary, key c exist in the dictionary. ... Program finished with exit code o Press ENTER to exit console.O