trying to add Go Back” function in WebView inside Fragment, but its showing this error - android-webview

This is my code
ERROR - " Type mismatch: inferred type is Unit but Boolean was expected "
webview2.setOnKeyListener(View.OnKeyListener {
fun onKey( int: Int, event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN){
if(int == event.keyCode){
if( webview2!=null){
if (webview2.canGoBack()){
webview2.goBack()
} else{
activity?.onBackPressed()
}
}
}
}
return true;
}
})

Related

"Expression type 'Bool' is ambiguous without more context" in ternary operation

I am trying to pass an enum to a function that does an operation on that enum's arguments. I receive this error:
Expression type 'Bool' is ambiguous without more context
The same error happens in an equivalent if clause, so it's not the ternary operator itself that causes the problem.
enum auto {
case pkw (SerialNumber: String, Axles: Int, Weight: Float)
case lkw (SerialNumber: String, Axles: Int, Weight: Float)
}
func checkIntegrity(car: auto) -> Bool {
switch car {
case .pkw:
if (checkSerialNumber(serialNumber: .pkw.SerialNumber.rawValue)
&& checkWeight(weight: .pkw.Weight.rawValue)) { // Error here, "&&" is underlined
return true
} else {
return false
}
break;
case .lkw:
return (checkSerialNumber(serialNumber: .lkw.SerialNumber.rawValue)
&& checkWeight(weight: .lkw.Weight.rawValue)) ? true : false; // same error here, "&&" is underlined
break;
default:
return false
}
The other functions that are called just return a Bool:
func checkSerialNumber(serialNumber: String) -> Bool {
return serialNumber.contains("ABABWA") // changed after a hint in the comments
}
func checkWeight(weight: Float) -> Bool {
return (weight < 2)
}
I am suspecting something wrong with the enum and how I use them, but I haven't found the solution yet.
The error message is misleading. You want to check the associated values
of an enumeration value, therefore you must bind those in the case pattern:
func checkIntegrity(car: auto) -> Bool {
switch car {
case let .pkw(serialNumber, _, weight):
if checkSerialNumber(serialNumber: serialNumber)
&& checkWeight(weight: weight) {
return true
} else {
return false
}
break;
case let .lkw(serialNumber, _, weight):
return (checkSerialNumber(serialNumber: serialNumber)
&& checkWeight(weight: weight)) ? true : false;
break;
default:
return false
}
}
This can be simplified to
func checkIntegrity(car: auto) -> Bool {
switch car {
case let .pkw(serialNumber, _, weight),
let .lkw(serialNumber, _, weight):
return checkSerialNumber(serialNumber: serialNumber) && checkWeight(weight: weight)
}
}

Enum pattern matching as a parameter to a function call

I've setup a playground with an example:
enum CarType : Equatable {
case wheeled(wheels: Int)
case flying
public static func ==(lhs: CarType, rhs: CarType) -> Bool {
return lhs.enumName == rhs.enumName
}
var enumName: String {
let stuff = "\(self)".split(separator: "(").first!
return String(describing: stuff)
}
}
var typesPresentAtMyParty = [CarType.wheeled(wheels:4), .wheeled(wheels:4), .flying]
let aKnownType = CarType.flying
if case aKnownType = typesPresentAtMyParty[2] {
print("Was the type")
}
func isPresent(type: CarType, inArray: [CarType]) -> Bool {
return inArray.filter {
if case type = $0 {
return true
}
return false
}.first != nil
}
func isWheeled(inArray: [CarType]) -> Bool {
return inArray.filter {
if case .wheeled = $0 {
return true
}
return false
}.first != nil
}
isPresent(type: .flying, inArray: typesPresentAtMyParty)
isPresent(type: .wheeled, inArray: typesPresentAtMyParty)
The last line here does not compile. While i can do if case .wheeled = $0 ignoring associated type as a check, i cannot find a way of doing the same in a function call isPresent(type: CarType, inArray: [CarType]), when sending isPresent(type: .wheeled, inArray: typesPresentAtMyParty)
Is there a way of writing a function that takes only the valid pattern matching part of the enum as a parameter?
It is not possible to pass partially constructed enums to a function. Partially constructed enums are not valid values, and they only work in pattern matching because the compiler has a concrete value to work with - the one from the right side of the pattern.
These being said, you could easily rewrite your functions to better, more swiftier versions.
Firstly, you don't need isPresent, you can simply use contains:
typesPresentAtMyParty.contains { $0 == .flying }
typesPresentAtMyParty.contains { if case . wheeled = $0 { return true } else { return false } }
Similarly, isWheeled can be shortened (and renamed, for better semantics):
func isWheeled(_ carType: CarType) -> Bool {
if case . wheeled = carType { return true } else { return false }
}
which can pe passed to contains:
let hasWeeled = typesPresentAtMyParty.contains(where: isWheeled)

Swift error: Missing return in a function expected to return 'String'

I'm trying to add edit some code from Apple's QuestionBot. I came up with this:
func responseToQuestion(question: String) -> String {
if question.hasPrefix("hello") {
return "Hello"
} else if question.hasPrefix("where") {
return "There"
} else if question.hasPrefix("what"){
return "I don't know"
}
}
But there's an error: Missing return in a function expected to return 'String'. What should I do, thanks?
Missing return in a function expected to return 'String'
should the function return something , because you did not set return if do not match any one question.hasPrefix()
func responseToQuestion(question: String) -> String {
if question.hasPrefix("hello") {
return "Hello"
} else if question.hasPrefix("where") {
return "There"
} else if question.hasPrefix("what"){
return "I don't know"
}
return "something"
}

Swift: Array contains(AnyObject) error Cannot convert type of ... throw -> Bool

Why I use Array.contains(AnyObject) to checking whether an structure object exists in this Array. It makes error : "Cannot convert type of ... throw -> Bool"
struct DecorationPatternsData {
let patternImageName: String
init(patternImageName: String) {
self.patternImageName = patternImageName
}
}
var decorationPatterns : [DecorationPatternsData] = [DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif")]
var pickedDecorationPattern : DecorationPatternsData? = nil
...
if (pickedDecorationPattern != nil) {
if (decorationPatterns.contains(pickedDecorationPattern)) {
// Error: Cannot convert type of ... throw -> Bool
}
}
That's because your DecorationPatternsData doesn't conform to Equatable which is a requirement for contains(_:) to work.
Solution 1:
extension DecorationPatternsData: Equatable { }
func ==(lhs: DecorationPatternsData, rhs: DecorationPatternsData) -> Bool {
return lhs.patternImageName == rhs.patternImageName
}
Now DecorationPatternsData conforms to Equatable so you can use:
if let pickedDecorationPattern = pickedDecorationPattern {
if decorationPatterns.contains(pickedDecorationPattern) {
// Your code
}
}
Solution 2:
if decorationPatterns.contains({ $0 == pickedDecorationPattern }) {
// Your code
}
Here you're using a closure to compare the elements, returning a bool for contains(_:)
...
if let pickedDecorationPattern = pickedDecorationPattern {
if decorationPatterns.contains(pickedDecorationPattern) {
// Error: Cannot convert type of ... throw -> Bool
}
}

"Missing return in a closure expected to return 'SomeType'" error in .map

I have the fallowing code:
struct AInt {
var aInt: Int
}
struct ADouble {
var aDouble: Double
static func convert(aInt: AInt) throws -> ADouble {
return ADouble(aDouble: Double(aInt.aInt))
}
}
struct B {
func doAction(aInts: [AInt]) throws -> [ADouble] {
return aInts.map { aInt in
do {
try ADouble.convert(aInt)
}
catch {
print(error)
}
}
// ^^^ error here: Missing return in a closure expected to return 'ADouble'
}
}
let aInts = [AInt(aInt: 2), AInt(aInt: 3)]
let b = B()
do {
print(try b.doAction(aInts))
}
catch {}
When i'm trying to convert [AInt] to [ADouble] in .map using function that can throw error, i get this error:
Missing return in a closure expected to return 'ADouble'.
Well, i decided to add return statement in the end of .map like this:
return aInts.map { aInt in
do {
try ADouble.convert(aInt)
}
catch {
print(error)
}
return ADouble(aDouble: 2.2)
}
Error disappear, but when i print try b.doAction(aInts) on same aInts array, i get this: [ADouble(aDouble: 2.2), ADouble(aDouble: 2.2)], i.e. it prints my ADouble(aDouble: 2.2) that i set manually. Obviously, it's not what i want, so then i try to add return before try ADouble.convert(aInt) like this:
return aInts.map { aInt in
do {
return try ADouble.convert(aInt)
}
catch {
print(error)
}
return ADouble(aDouble: 2.2)
}
And now i get right result: [ADouble(aDouble: 2.0), ADouble(aDouble: 3.0)]. But this code still doesn't work without return statement in the end of the .map. Any ideas how to get rid of it?
The map() method is declared as
#rethrows public func map<T>(#noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]
which means (if I understand it correctly) that the transform can
either return a value or throw an error (and this will be
forwarded to the caller).
This compiles and works as expected:
struct B {
func doAction(aInts: [AInt]) throws -> [ADouble] {
return try aInts.map { aInt in
return try ADouble.convert(aInt)
}
}
}
An error thrown from ADouble.convert(aInt) will be forwarded to
the caller of map() and from there to the caller of doAction().