Missing return in a function expected to return 'Double?'
Your function can be shortened a hell of a lot by taking advantage of some of the tools that’s Swift gives you. Here, take a look, this does the same thing...
func priceCheck(name: String) -> Double? {
guard let stockAmount = stock[name],
stockAmount > 0,
let price = prices[name] else {
return nil
}
return price
}
Error: 'Missing return in a function expected to return Int'
You also need to consider cases that do not fall in the 2 conditions. It expects you to provide a default return value.
In the first case, you had a default value of 0 being returned.
In the second case, if your frequency
is neither in the first range (specified by the first if
condition) nor in the second range (specified by the second if
condition), you need to specify a default return value.
func isBandFM() -> Int {
if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxFMFFrequency {
return 1 //FM
} else if frequency >= RadioStation.minAMFFrequency && frequency <= RadioStation.maxAMFFrequency{
return 0 //AM
}
return 0 // or whatever value you want to return if frequency is not within FM range or AM range
}
missing return in a function expected to return 'Double' | What to do?
The issue is that your if
statement is missing an else
block, the return value is not defined for the case when self == 0
. You can simply change the else if
branch to else
, because you also want to return self
for 0
.
var absoluteValue: Double {
if self < 0 {
return self * -1
} else {
return self
}
}
You can also write this as a oneliner using the ternary operator:
var absoluteValue: Double {
return self < 0 ? self * -1 : self
}
Missing return in a function Swift
What happens if player1TotalScore
is less than player2TotalScore
. It falls through both if
conditions and has no return value. You have to handle every case, and you're missing one here. That's why the else
works, it handles both the ==
and the <
cases.
Related Topics
iOS Charts 3.0 - Align X Labels (Dates) with Plots
@Objc Keyword Extension Subclass Behaviour
Using Non Ns_Enum Objective-C Enum in Swift
How Is Optional Binding Used in Swift
Self' Captured by a Closure Before All Members Were Initialized
Converting a C-Style for Loop That Uses Division for the Step to Swift 3
Does a Mutating Struct Function in Swift Create a New Copy of Self
Get an Array of Dates of the Current Week Starting on Monday
Segue from a Slpagingviewswift Vc and Dismiss the Destination Vc to Return
What Is a 'Non-Nominal Type' in Swift
Swift's JSONdecoder with Multiple Date Formats in a JSON String
Swift - Drawing Text with Drawinrect:Withattributes:
Swiftui - Two Buttons in a List
How to Get the Height of a Uilabel in Swift
When and How to Use @Noreturn Attribute in Swift
Create Nsmanagedobject Subclass... Make a New Error in My Project