boolean - Compare value and return a bool in Swift -


i converting code objective-c swift. declared function compare values of 2 properties , return bool. , confused why code not work in swift.

private var currentlinerange: nsrange? var location: uint?  func atbeginningofline() -> bool {     return self.location! == self.currentlinerange?.location ? true : false } 

compiler gave me error:

could not find overload == accepts supplied arguments

thanks.

you have 2 optional values , want check if they’re equal. there version of == comparing 2 optionals – need of same type.

the main problem here comparing nsrange.location, int, location, uint. if tried without complication of optionals, you’d error:

let ui: uint = 1 let i: int = 1 // error: binary operator '==' cannot applied operands of  // type 'int' , ‘uint' == ui   

there’s 2 ways can go. either change location int, , you’ll able use optional ==:

private var currentlinerange: nsrange? var location: int?  func atbeginningofline() -> bool {     // both optionals contain int, can use == on them:     return location == currentlinerange?.location } 

or, if location need uint other reason, map 1 of optionals type of other compare them:

private var currentlinerange: nsrange? var location: uint?  func atbeginningofline() -> bool {     return location.map { int($0) } == currentlinerange?.location } 

one thing careful of – nil equal nil. if don’t want (depends on logic you’re going for), need code explicitly:

func atbeginningofline() -> bool {     if let location = location, currentlinerange = currentlinerange {         // assuming want stick uint         return int(location) == currentlinerange.location     }     return false // if either or both nil } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -