The if let
construct is used for "conditional binding" of an optional. The thing you are trying to assign to name
(the function result) is not optional - instead, the value you are passing to String(cString:,name:)
is optional.
You should rewrite your code to something like this:
if let interfaceName = interface?.ifa_name {
let name = String(cString: interfaceName)
if name == "utun0" {
print("Ipfound")
ipFound = true
} else {
print("name != Ipfound")
}
} else {
print("interface or interface.ifa_name is nil")
}
In that code I'm using optional binding to try to get a non-nil value from interface?.ifa_name
.
If you use !
"force unwrap" operator as you were trying to do, your code would crash if interface
is nil, or if interface.ifa_name is nil.
Edit:
Another way you could handle this, that would look closer to your original code, would be to use map()
on the Optional
:
if let name: String = interface?.ifa_name.map ({ String(cString: $0)}),
name == "utun0" }
{
print("Ipfound")
ipFound = true;
}
The form of map()
that works on an Optional takes an Optional as input. If that optional is nil, it returns nil. If the optional is not nil, the result returned by map()
is the result of applying your closure to the unwrapped optional.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…