Check this code on xcode playground
I am trying to get the longest prefix substring from string in swift.
This solution is working but I have a question
the min function is not giving me desired “swim” as shortest string
`
var string = "swimftch swim swimftc swill"
let splitArray = string.split(separator: " ")
var shortestString = string
for singleString in splitArray {
//This works fine - gives "swim" as desired
// if shortestString.count > singleString.count {
// shortestString = String(singleString)
// }
//this does not - gives "swill"
shortestString = min(String(singleString), shortestString)
print(shortestString)
}
var isPrefixed = false
func checkSubString() {
for sub in splitArray {
if sub.contains(shortestString) {
print(shortestString)
isPrefixed = true
} else {
isPrefixed = false
}
}
if !isPrefixed {
shortestString.popLast()
checkSubString()
} else {
print(shortestString)
}
}
checkSubString()
`
Can anyone explain this to me, why min is not returning the shortest substring correctly?
for singleString in splitArray {
//This works fine - gives "swim" as desired
// if shortestString.count > singleString.count {
// shortestString = String(singleString)
// }
//this does not - gives "swill"
shortestString = min(String(singleString), shortestString)
print(shortestString)
}
New contributor
Neeraj kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.