Skip to content

Instantly share code, notes, and snippets.

@bhakes
Last active November 6, 2018 17:26
Show Gist options
  • Save bhakes/44cdb697579949b128b3f5d55800e16a to your computer and use it in GitHub Desktop.
Save bhakes/44cdb697579949b128b3f5d55800e16a to your computer and use it in GitHub Desktop.
/** iOS4CodeChallenge-18.11.06.md
* By Ben H
*/
// instantiate testing arrays
let stringArray = ["test", "test1", "test2", "test33"]
let stringArray2 = ["test", "test133", "test2", "test33"]
let stringArray3 = ["test", "test1", "test2", "test3"]
// function to find the longest string in a string array
public func longestString(within pStrArray:[String]) -> String{
var longestStr: String = pStrArray[0]
var longestStrLen: Int = pStrArray[0].count
// check if string is the longest, set to longestStr if so
for string in pStrArray{
if(longestStrLen < string.count){
longestStrLen = string.count
longestStr = string
}
}
return longestStr
}
// report func results on testing arrays
let out = longestString(within: stringArray)
let out2 = longestString(within: stringArray2)
let out3 = longestString(within: stringArray3)
print(out)
print(out2)
print(out3)
@dillon-mce
Copy link

Looks good. It definitely works as long as there is at least one string in the array. It crashes if there is no value at pStrArray[0]. Swift Arrays have a property .first which returns the first element if it exists or nil if it doesn't. That is probably safer (and "swifter").

You also probably want to be careful declaring things as public. It won't matter in this case, but generally you want the smallest scope that works for what you're trying to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment