当前位置:  开发笔记 > IOS > 正文

二进制运算符'&'不能应用于'SCNetworkReachabilityFlags'和'Int'类型的操作数

如何解决《二进制运算符'&'不能应用于'SCNetworkReachabilityFlags'和'Int'类型的操作数》经验,为你挑选了1个好方法。

我尝试检查我的应用程序中的互联网连接时收到此错误.

我使用Xcode 7.1.1 Swift 2.0

代码块如下

public class Reach {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))//.takeRetainedValue()
    })

    var flags: SCNetworkReachabilityFlags = []
    if SCNetworkReachabilityGetFlags( defaultRouteReachability!, &flags) == false {
        return false
    }

    //The following two lines shows the error
    let isReachable = (flags  & (kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags  & (kSCNetworkFlagsConnectionRequired)) != 0

    return isReachable && !needsConnection
}

}

我尝试将标志转换为Int和NetworkFlag转换为UInt32,反之亦然但仍显示警告并在执行时出错.我尝试了以下内容

(flags  & UInt32(kSCNetworkFlagsReachable))
(Int(flags)  & (kSCNetworkFlagsReachable))
(flags  & (kSCNetworkFlagsReachable) as! UInt32)
(flags as! Int  & (kSCNetworkFlagsReachable))

但没有任何效果.任何人都可以解决它

SCNetworkReachabilityFlags的内容

public struct SCNetworkReachabilityFlags : OptionSetType {
public init(rawValue: UInt32)

public static var TransientConnection: SCNetworkReachabilityFlags { get }
public static var Reachable: SCNetworkReachabilityFlags { get }
public static var ConnectionRequired: SCNetworkReachabilityFlags { get }
public static var ConnectionOnTraffic: SCNetworkReachabilityFlags { get }
public static var InterventionRequired: SCNetworkReachabilityFlags { get }
public static var ConnectionOnDemand: SCNetworkReachabilityFlags { get } // __OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_3_0)
public static var IsLocalAddress: SCNetworkReachabilityFlags { get }
public static var IsDirect: SCNetworkReachabilityFlags { get }

public static var IsWWAN: SCNetworkReachabilityFlags { get }
// TARGET_OS_IPHONE

public static var ConnectionAutomatic: SCNetworkReachabilityFlags { get }

}



1> Fonix..:

试试吧

let isReachable = flags.contains(SCNetworkReachabilityFlags.Reachable)
let needsConnection = flags.contains(SCNetworkReachabilityFlags.ConnectionRequired)

该OptionSetType有一个方便的方法包含,所以希望如果设置了标志,将检查

推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有