Swift - what does Optional mean in log output? [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
When I get the value from a Text Field and cast it to an integer, I get log output that says Optional(5) if I inputted 5, or Optional(1234) if I inputted 1234.
What does Optional() mean?
Here is the code to get and cast the value:
#IBOutlet weak var myInput: UITextField!
// When a button is clicked, I log the value in the UI text field.
#IBAction func someButton(sender: AnyObject) {
println(self.myInput.text.toInt())
}

Optional means the value is Optional type. It can be either nil or a value. When working with cocoa api most of the method parameters are optional type. To get actual value from optional value you either use if-let binding or force it to unwrap it with ! operator. Suppose ve have a value of a optional type of Int. Let's define it first.
let a: Int? = 5
The ? denotes it is an optional value. If you print this a it will write Optional(5). Let's get the actual value from it.
if let actualA = a {
println(actualA)
}
Now if a is not nil then the code inside if-let statement will be executed and it will print 5 on the console.
Optional types are for dealing with nil values in swift. They provide extra safety when working parameters and variables. If a value is not optional than it can never be nil. So we can safely do our work without worrying about nil values.

Related

Difference between print(nil) and print(name) when var name: String? = nil

I'm a student who's new in Swift.
While I'm studying about the Optional, I got curious about the keyword nil, so I tried some experiment with it. I'm using Swift version 5.5.
As you can see in the image below, if I assign nil to a optional variable (which I named 'name') and then print it with print(name) and print("(name)") (string interpolation), I got nil on the console in both cases. (Line 5, 9)
But when I print nil without the optional variable, which I printed it with print(nil) and print("(nil)"), I got an error on both cases. (Line 7, 11)
I expected them all to print out nil but they didn't.
I really want to know the difference between those cases.
The issue is that nil isn't just one single value, like null in Java/C#.
nil is syntactic sugar for Optional<Wrapped>.none. There's one different kind of value for every possible Wrapped. E.g. there is Optional<Int>.none and Optional<String>.none, and you can't assign from one to the other, because they're unrelated types.
When you use nil, the value of the Wrapped generic parameter is inferred from context, much like when you do:
let a = Optional<Int>.none // most explicit
let b: Optional<Int> = Optional.none // Generic Wrapped param inferred from the type annotation
let c: Optional<Int> = nil // Same inference
print takes an Any, so that doesn't give any relevant contextual type information. When you say print(nil), it's not clear what the typed of Wrapped should be. You might not care (because Optional<Int>.none and Optional<String>.none both print "nil"), but the type system can't leave it open ended, so it's a type error.
If you added contextual type information, it works, such as using a variable of a known type, or using a coercion:
print(nil as String?)
Interesting question actually. If you look at the Swift documentation:
Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.
So think of it as nil is the absence of some value. As an example if you have:
var name: String?
name can either be a string value, or the absence of a string value.
So it makes no sense to try and print nil explicitly since you already know that it's the absence of a value, however, it makes sense to print name to check if it has a string value and in that case what it is, or if it has no string value.
The error message in XCode tells you exactly what happens: nil is not compatible with expected argument type Any - the print function expects a non-nil argument, as does the string interpolation with \(),

what is the difference between `?` and `!` in swift? [duplicate]

This question already has an answer here:
Swift variable decorations with "?" (question mark) and "!" (exclamation mark)
(1 answer)
Closed 2 years ago.
I have this doubt when I run this code both of them give me the same datatype as result. I know I am missing something really basic can someone please explain why ! and ? on a type gives the same datatype as result?
import UIKit
import Foundation
var unwrappedString: String!
var optionalString: String?
print("type of unwrappedString is:", type(of:unwrappedString))
print("type of optionalString is:", type(of:optionalString))
output is
type of unwrappedString is: Optional<String>
type of optionalString is: Optional<String>
Both symbols ! and ? used for optionals. We should have to use !, when we make sure option type variable has value at a time and we need to take action on it. Otherwise it will crash if variable value is nil nd if you are using ?, Application will not crash in nil case.

iOS String: remove prefix and suffix by CharacterSet [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
For a given String in Swift I need to remove prefix and suffix characters that belong to a predefined character set.
I can use components(separatedBy:) with the character set and get rid of the empty strings at the beginning and end of the components array. Just wondering if there's a better approach?
Thanks!
You can use .trimmingCharacters(in: CharacterSet) on the string. From the 'help' text in Xcode on this function: "Returns a new string made by removing from both ends of the String characters contained in a given character set."
Here is a unit test example using a custom character set. Notice it only removes characters from the start and end, not the middle (the comma stays):
import XCTest
class TrimCharacters: XCTestCase {
func testExample() throws {
let string = "abcbaHello, World!ccbbaa"
let charactersToTrim = CharacterSet(charactersIn: "abc,")
XCTAssertEqual(string.trimmingCharacters(in: charactersToTrim), "Hello, World!")
}
}
There are also predefined character sets that can be useful. You can also invert a character set. See CharacterSet

While "Printf" in swift getting "optional" text before actual text [duplicate]

This question already has answers here:
Printing optional variable
(15 answers)
Closed 7 years ago.
I am trying to print value on my table view row everything goes correct but value is printing like
println("\(cell?.textLabel?.text)")
Optional("Some text") instead of "Some text"
Is there any way in swift to print actual value?
It is printing an optional values so you need to unwrap it like:
if let yourCell = cell?.textLabel?.text {
println(yourCell)
}
Refer this Apple Document to know more about optionals.
print like this
println(cell.textLabel?.text)

What the meaning of question mark '?' in swift? [duplicate]

This question already has answers here:
What is an optional value in Swift?
(15 answers)
Closed 8 years ago.
In Swift programming I found some question marks with objects.
var window: UIWindow?
Can anybody explain the use of it?
You can use if and let together to work with values that might be
missing. These values are represented as optionals. An optional
value either contains a value or contains nil to indicate that the
value is missing. Write a question mark (?) after the type of a value
to mark the value as optional.
If the optional value is nil, the conditional is false and the code in
braces is skipped. Otherwise, the optional value is unwrapped and
assigned to the constant after let, which makes the unwrapped value
available inside the block of code.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pk/jEUH0.l
For Example:
var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
In this code, the output would be Hello! John Appleseed. And if we set the value of optionalName as nil. The if conditional result would be false and code inside that if would get skipped.
Question marks after a type refer to Optionals, a way in Swift which lets you indicate the possibility that a value might be absent for any type at all, without the need for special constants.
It's used in the same situations you'd explicitly return nil in Objective-C, when there is no object to be returned, or for values that are not objects, constants such as NSNotFound. Optionals provide a consistent way of achieving this across all data types.
From the Apple provided iBook
You use optionals in situations where a value may be absent. An
optional says:
There is a value, and it equals x
or
There isn’t a value at all
Here’s an example. Swift’s String type has a method called toInt,
which tries to convert a String value into an Int value. However, not
every string can be converted into an integer. The string "123" can be
converted into the numeric value 123, but the string "hello, world"
does not have an obvious numeric value to convert to.
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int"
Because the toInt method might fail, it returns an optional Int,
rather than an Int. An optional Int is written as Int?, not Int. The
question mark indicates that the value it contains is optional,
meaning that it might contain some Int value, or it might contain no
value at all. (It can’t contain anything else, such as a Bool value or
a String value. It’s either an Int, or it’s nothing at all.)
There is a whole section on the language reference iBook on Optionals, and they are mentioned several times throughout the book. You should have a thorough look at it, since it's a fundamental concept of Swift programming, and one that is not prevalent in many other languages.
the optional Value of the type .
For Ex :
the optional version of the type casting operator : as? ,mean as use for the type casting with might be optional to cast .

Resources