Putting it all together
To reinforce what we have learned in this chapter, let's look at one more example. For this example, we will create a function that will test whether a string value contains a valid IPv4 address. An IPv4 address is the address assigned to a computer that uses the Internet Protocol (IP) to communicate. An IP address consists of four numeric values that range from 0-255
, separated by a dot (period). The following is a code example of a valid IP address; that is, 10.0.1.250
:
func isValidIP(ipAddr: String?) ->Bool {
guard let ipAddr = ipAddr else {
return false
}
let octets = ipAddr.split { $0 == "."}.map{String($0)}
guard octets.count == 4 else {
return false
}
for octet in octets {
guard validOctet(octet: octet) else {
return false
}
}
return true
}
Since the sole parameter in the isValidIp()
function is an optional type, the first thing we do is verify that...