Return nil in swift function
To fix the error you need to return an Optional: List?
func listForName (name: String) -> List? {
if let list = listsDict[name] {
return list
} else {
return nil
}
}
Or just return listsDict[name]
since it will either be optional or have the list itself.
func listForName (name: String) -> List? {
return listsDict[name]
}
But i don't want to return something like empty List object, i want to return nothing when optional is empty. How to do that?
You have several choices:
- Return optional List (List?)
- Return an empty list when no data is found
- Return an exception (depends on context)
- Use an enum to represent Either/Result (similar to Optional but could be better depending on your use-case)
Are `return nil` and `return` interchangeable?
Nope they're not the same.
Returning nil
is used when you need to return a value but that value can be optional. So in your example:
func naming(name: Int) -> String? {
switch name {
case 0: return "Neo"
case 1: return "Matrix"
default: return nil
}
}
The function is expecting a String
OR a nil
value to be returned, hence String?
. The question mark on the end indicates that the String
is optional. When you call naming(name: 2)
that calls the switch
statement and doesn't find a value corresponding to the number 2, so defaults to returning nil
.
Putting return
like in your second example just stops the rest of the function from executing. So:
function loadVideo() {
guard let video = try? avplayer else {
print("Unable to load a movie")
return
}
print("hello")
}
If the avplayer
variable is nil then the guard
statement will execute its else
statement and print out Unable to load a movie
then return
from the function. This will prevent hello
from being printed.
Do i have to state a return nil statement when my return value in a function is an optional?
Just to clarify:
Parameter:
mealTime: String
This string could be a key in your dictionary.
Function (how it works): this function wants to check if this key exists and if it is so, it returns the value (that is a Meal object).
What did you do?
if let a = meals[mealTime] {
return a
} else {
return nil
}
You are checking (if let) if there is a value with that string key and you are assigning that value to your constant (a). Eventually you return that value. If no value has that key in your array then you return nil.
- What is the right answer about?
Because this function returns an Optional Meal, you can skip checking if it exists, that's why the right answer is just:
func logging(mealTime: String) -> Meal? {
return meals[mealTime]
}
This function returns nil if there is not value with that key and returns the value if it has that key.
How to return in a function if a variable is nil?
Not wanting to use a default value and just wanting the function to return is exactly what guard
statements are for:
func yourFunction() {
guard let enteredTargetDays = numberFormatter.number(from: textField2.text ?? "")?.doubleValue else {
return
}
// do something with `enteredTargetDays` here
}
Use map to return nil for an optional value
Simple, you want flatMap
instead of map
. It behaves in exactly the same way, but it strips optionals out.
func mapTest(value: Bool?) {
var dataTest: String?
dataTest = value.flatMap({ val in
if val {
return ""
}
return nil
})
}
how do you return nil if a certain type is passed to a function in Swift?
You are passing blog
as a BlogPost.Type
parameter. That is not correct. You should have either just passed it the String
parameter, or you could pass it the BlogPost
itself:
func randomViews(blog: BlogPost) {
let videos = types[2]
if blog.type == videos {
// do whatever you want
}
// carry on
}
Unrelated to your question at hand, but notice that I use let
instead of var
when defining videos
. Always use let
if the value will not (and cannot) change.
Also note that I use lowercase letter v
in videos
, because Cocoa naming conventions dictate that variables generally start with lowercase letters, whereas types, classes, structs, and enums generally start with uppercase letters.
How to return nil object in non void function - swift 2.1?
Use “?” with function’s return type instead
replace "class func getUserFromUserID(userID:String)->Table_Users" with "class func getUserFromUserID(userID:String)->Table_Users?"
Updated Code:
class Table_Users: NSManagedObject {
class func getUserFromUserID(userID:String)->Table_Users?
{
var user:Table_Users? = nil
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate
{
let moc = delegate.managedObjectContext
}
else
{
}
return user
}
}
Related Topics
Swift 4 Codable - API Provides Sometimes an Int Sometimes a String
How to Nskeyedunarchiver.Unarchiveobject
Testing an Executable with Swift
Scene Created in Sprite Kit Level Editor Is Not Working
Xcode Swift How to Add Image to Uialertcontroller Options
Separation of Function Declaration and Definition in Swift
Swift: Unable to Decompose Tuple in Certain Closures (E.G., Reduce with Enumerate)
How to Get Date and Time to Show a Clock in Uilabel
How to Make Alphabetically Section Headers in Table View with a Mutable Data Source
Adding a Search Bar to Navigationview in Swiftui
What Is the Backslash(\) Used for in Swiftui
Swift Package Manager - Type 'Bundle' Has No Member "Module" Error
Iterating with for .. in on a Changing Collection