Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

swift - Initializer for conditional binding must have Optional type, not 'String' not working after clean build

swift code is not working after clean build.

how can i rewrite this simple code?

if let name: String = String(cString: (interface?.ifa_name)!), name == "utun0" {
                    print("Ipfound")
                    ipFound = true;
                }

i put image for better understanding.

enter image description here

question from:https://stackoverflow.com/questions/65942310/initializer-for-conditional-binding-must-have-optional-type-not-string-not-wo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...