Created
September 16, 2020 20:09
-
-
Save decodeveronikaa/5b497dd74f7710461601c0065561c0c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
var str = "Hello, playground" | |
import XCTest | |
/* Return the middle | |
Write a function that returns the middle element of an array. When array size is even, return the first of the two middle elements. | |
*/ | |
func middle(_ array: [Int]) -> Int? { | |
// TODO: - Put your code here | |
if array.count == 0 { | |
return nil | |
} else { | |
var middleIndex = array.count / 2 | |
if array.count % 2 == 0 { | |
middleIndex -= 1 | |
} | |
return array[middleIndex] | |
} | |
} | |
/* Merge dictionaries | |
Write a function that combines two dictionaries into one. If a certain key appears in both dictionaries, ignore the pair from the first dictionary. | |
*/ | |
func merging(_ dict1: [String: String], with dict2: [String: String]) -> [String: String] { | |
// TODO: - Put your code here | |
var pairs: [String: String] = [:] | |
for (key, value) in dict1 { | |
pairs[key] = value | |
} | |
for (key, value) in dict2 { | |
pairs[key] = value | |
} | |
return pairs | |
} | |
/* Write a function that will run a given closure a given number of times. | |
*/ | |
func repeatTask(times: Int, task: () -> Void) { | |
if times > 0 { | |
for i in 1...times { | |
task() | |
} | |
} | |
} | |
/* Write a function which takes a string and returns a version of it with each individual word reversed. | |
For example, if the string is “My dog is called Rover†then the resulting string would be "yM god si dellac revoR". | |
Try to do it by iterating through the indices of the string until you find a space, and then reversing what was before it. Build up the result string by continually doing that as you iterate through the string. | |
*/ | |
func reverseWords(_ string: String) -> String { | |
// TODO: - Your code goes here | |
var reversed = "" | |
var words = string.split(separator: " ") | |
if words.count == 0 { | |
return reversed | |
} | |
for i in 0...words.count - 1 { | |
let word = words[i] | |
reversed.append(String(word.reversed())) | |
if i < words.count - 1 { | |
reversed.append(" ") | |
} | |
} | |
return reversed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment