I'm new to the Swift language and until this point i only worked in web development.
I tried to grasp the idea of optionals, but every time they present some situation where to use it, I still can't understand why they do so (or I might have a little idea, but still not sure.)
I read several articles about this and maybe I just got too confused about it along the way and got lost.
So let's present some examples. Let's say I have a registration form with a textfield for an e-mail. After the form is sent, in PHP I could do something like:
$mail = $_POST['mail'];
if($mail == "") {
echo "ERROR: The E-mail is empty";
} else {
// Do something more
}
If the textfield is empty, the value of $_POST['mail'] is an empty string. I can work with that and check if it is empty or not.
Now, if I understand correctly, in swift the value of that textfield wouldn't be an empty string, but actually a nil, right? Is this that kind of a difference why we need optionals? Because in comparison to PHP, in Swift I have to declare the type of that information each time and it doesn't know if that textfield passes strings or numbers?
Let's talk about another example. Lot of people in swift just declare a string as an optional, even if they put a value in it, like so:
let name:String? = "Gabriel"
If it already has a value, why make it an optional then? For me, it is just a normal constant with a value and I don't see the point of wrapping it into an optional.
If I don't know the name at the declaration, why can't i just type this?
let name:String = ""
and after that, I can use an if statement to check if it is empty or not
if name == "" {
print("ERROR: name is empty")
} else {
//Do something else
}
Did I get the idea with the textfield right or not?
Is there something I'm missing?
Thank You for any help!
EDIT (What got me understanding the concept):
What I got confused about the most was the simple fact, that for example a String can store only "text" and that if nil was something, it wouldn't be of type String, so therefore it couldn't be "stored" inside String of course.
Just in the same way, as I can't store text into an Integer — I can't "store" nil into a String.
But with Optional String I can use this "wrapper" that actually CAN "store" both types: string or nil. And that is what distinguish regular String from Optional String. It is this "wrapper" that has the ability to "hold" both these types until I need to use the actual value. (Now of course I understand, that nil is actually an absence of any value. I just used it in this way to illustrate the point)
Thank You everyone for Your help!
Imagine you ordered a playstation from ebay. The first thing you see is not the playstation, but a box. So, in this instance, the box is an optional. Let's write it down.
var playstation: Playstation?
The box can of course be empty. In order to use the playstation, we need to open the box. We have several ways to do that.
The safe way:
if let ps = playstation {
// if the box is not empty, and the PS is there
ps.play()
} else {
print("The box was empty :(")
}
The other way:
playstation?.play()
In this other scenario, we're only calling the play() method if the contents of playstation box are not empty. Downside is that you cannot display an error in case it fails.
What if you promised your friend that you'll play together on your playstation that will be here today. You're giving a guarantee that the playstation will be in the box. That's when you use this:
playstation!.play()
Problem with this approach, in actual programs, is that your app will crash if the contents of the optional are empty. Use "!" only if you can guarantee that it will not be empty (i.e. you assigned a value to the variable right before this)
So, to conclude, optionals are variables whose value can be either a specific type (i.e. String) or nil. You cannot assign nil to strongly typed variables.
var a: String?
var b: String
a = nil // this is ok
b = nil // this will not compile
Think of optionals like this :
An optional is a variable which can be empty something in the future or even now.
Making a variable an optional means it is wrapped as an enum.
Suppose there is a variable : var x : Int?, this means a variable named x of type Int, is not yet initialised and an optional.
This typically can be represented in layman terms as
Enum x(optional) // name of the variable{
case T: // some value
case nil: // no value
}
So when we assign a variable we can just assign it normally, but the value is stored in the case T of the optional enum variable of x.
x = 10 //
enum x(optional){
case T = 10
case nil
}
When we want to use it(get the value) we use a (?) or an (!)
These can be farther explained as
print(x?) // If there is any value inside of x, give it to me(in this case give me the value of x's case of T)
print(x!) // I dont care if there is any value inside of x or not, just give it to me anyway.
Hence if x has no value then printing (x!) will produce a crash, as x does not have a value inside of it.
? - safely unwrapping the optional
! - force unwrapping the optional
P.S - I know there are certain things I missed but this is the jist of Optional is this is meant only for explanatory purpose. Once you grasp this concept you can farther check out more documents on Apple's documentation here
Effectively,
let name:String? = "Gabriel"
is not very useful.
But
var name:String? = "Gabriel"
does make sense, as you can further on set to nil.
Optionals are very useful for returning value from function.
Consider a func that returns an Int.
If the value is not found, you could return a number (like very large negative) to notify value was not found. But there is a risk some day that the func does return this value (even unlikely).
Returning a nil let the function make it clear it did not find the value.
My understanding of optionals is that they are a type just like String, or an Int, or a Double. Optionals have associated values so an String? is an optional with a String associated to it. The optional can either contain a value which is a string, even an empty string or nothing at all, which to me is null. Check out the Stanford U IOS course on iTunes. Optionals are explained much better then I am able to.
Related
I know that if a URL has something like http://example.com/test.html?id=2, then the ?id=2 is used to send the parameter values to the server requesting the current page.
Now if the URL is something like example.com/test.html?id, what does this mean?
I see this in a lot of sites these days. What does id provide?
i.e the id does not contain any value, then why use it ?
Example: example.net/eticketing/logout?out - what does the out provide to the server site?
PS: Assume PHP is the server side scripting language.
It is not really true in a strict sense that the query part of an url sends "values" to a server. Instead it is just a string that is interpreted by what ever processes that string on the server side, typically some scripting language.
Indeed typically some pattern like name=value will result in a variable called name holding the value value. But, as said, this is up to the processing step, it is not defined by some general standard.
There are a number of typical ways of how such a query string as you mention it, holding only some string but nothing like the pattern mentioned above, is interpreted:
a variable is created, but not assigned any value, since none has been specified inside the query string. This does make sense, since the presence of a variable already is a statement in itself that can be evaluated, thus it can influence the processing step.
the processing step can chose to completely skip the "typical" way such a string is interpreted and simply take over the value as given and do with it what it likes. That also does make a lot of sense, since typically such links are defined and handed out for usage by exactly the same processing step in a past request. So nothing speaks against that step to interpret the query in any way it thinks best suited.
often such string is not even handed over to the final processing step (some server side scripting language). Instead it only serves the purpose to be evaluated in some rewriting rule taking place inside the http servers routing step. This is a very easy and convenient way to hand over runtime information independent of the concept of a variable.
So the bottom line is: this completely depends in the server side processing step.
Parameter passed after ? in URL is accessed via $_GET.
This is a superglobal, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
If you have a query string that contains a parameter but no value (not even an equals sign), like so:
http://example.com/test.html?id
<pre>
<?php
print_r($_GET);
if($_GET["id"] === "") echo "id is an empty string\n";
if($_GET["id"] === false) echo "id is false\n";
if($_GET["id"] === null) echo "id is null\n";
if(isset($_GET["id"])) echo "id is set\n";
if(!empty($_GET["id"])) echo "id is not empty";
?>
</pre>
I tested this with http://example.com/test.html?id, and it returned:
id is an empty string
id is set
So note that a parameter with no value associated with, even without an equals sign, is considered to be an empty string (""), isset() returns true for it, and it is considered empty, but not false or null.
Thanks.
I want an SQL function to receive a string such as point_str = "47.572820 -34.628906". Inside the function, the string will be converted into a shape variable, for example by SET xpoint = PointFromText( concat("POINT(", point_str, ")") );
Before sending this string from php to sql, do I need to sanitize it (for example with floatval)?
You can throw an error on both situations; either when the text is entered, of when it is read. When the data is read and the function fails to genereate a shape, all visitors of that page will see the error.
If you throw the error on creation, there is only one person who gets an error plus the wrong data will never be in your database. So yes. If the output is dependent on the input make sure the input is suitable for the output and sanitize it.
I'm a PHP newbie trying to find a way to use parse_str to parse a number of URLs from a database (note: not from the request, they are already stored in a database, don't ask... so _GET won't work)
So I'm trying this:
$parts = parse_url('http://www.jobrapido.se/?w=teknikinformat%C3%B6r&l=malm%C3%B6&r=auto');
parse_str($parts['query'], $query);
return $query['w'];
Please note that here I am just supplying an example URL, in the real application the URL will be passed in as a parameter from the database. And if I do this it works fine. However, I don't understand how to use this function properly, and how to avoid errors.
First of all, here I used "w" as the index to return, because I could clearly see it was in the query. But how do these things work? Is there a set of specific values I can use to get the entire query string? I mean, if I look further, I can see "l" and "r" here as well...
Sure I could extract those too and concatenate the result, but will these value names be arbitrary, or is there a way to know exactly which ones to extract? Of course there's the "q" value, which I originally thought would be the only one I would need, but apparently not. It's not even in the example URL, although I know it's in lots of others.
So how do I do this? Here's what I want:
Extract all parts of the query string that gives me a readable output of the search string part of the URL (so in the above it would be "teknikinformatör Malmö auto". Note that I would need to translate the URL encoding to Swedish characters, any easy way to do that in PHP?)
Handle errors so that if the above doesn't work for some reason, the method should only return an empty string, thus not breaking the code. Because at this point, if I were to use the above with an actual parameter, $url, passed in instead of the example URL, I would get errors, because many of the URLs do not have the "w" parameter, some may be empty fields in the database, some may be malformed, etc. So how can I handle such errors stably, and just return a value if the parsing works, and return empty string otherwise?
There seems to be a very strange problem that occurs that I cannot see during debugging. I put this test code in just to see what is going on:
function getQuery($url)
{
try
{
$parts = parse_url($url);
parse_str($parts['query'], $query);
if (isset($query['q'])) {
/* return $query['q']; */
return '';
}
} catch (Exception $e) {
return '';
}
}
Now, obviously in the real code I would want something like the commented out part to be returned. However, the puzzling thing is this:
With this code, as far as I see, every path should lead to returning an empty string. But this does not work - it gives me a completely empty grid in the result page. No errors or anything during debugging, and objects look fine when I step through them during debugging.
However, if I remove everything from this method except return ''; then it works fine - of course the field in the grid where the query is supposed to be is empty, but all the other fields have all the information as they should. So this was just a test. But how is it possible that code that should only be able to return an empty string does not work, while the one that only returns an empty string and does nothing else does work? I'm thoroughly confused...
The meaning of the query parameters is entirely up to the application that handles the URL, so there is no "right" parameter - it might be w, q, or searchquery. You can heuristically search for the most common variables (=guess), or return an array of all arguments. It depends on what you're trying to achieve.
parse_str already decodes urlencoding. Note that urlencoding is a way to encode bytes, not characters. It depends on what encoding the application expects. Usually (and in this example query), that should be UTF-8 everywhere, so you should be covered on 1.
Test whether the value exists, and if not, return the empty string, like this:
$heuristicFields = array('q', 'w', 'searchquery');
foreach ($heuristicFields as $hf) {
if (isset($query[$hf])) return $query[$hf];
}
return '';
The function returns null if the input is valid, and runs into errors (i.e., displays warning messages) when the URL is obviously invalid. The try...catch block has no effect.
It turned out the problem was with Swedish characters - if I used utf8_encode() on the value before returning it, it worked fine.
I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.
A variable is NULL if it has no value, and points to nowhere in memory.
empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL.
The following things are considered to
be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Source.
Example
$a is NULL.
$a = '' is empty, but not NULL.
Update
If $a='' is empty but not NULL, when do I use the empty() function and when do I use the isset() function.
isset() will return FALSE is the variable is pointing to NULL.
Use empty() when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = '' will be in memory as a string with length of 0.
If it were $str = NULL, it would not occupy any memory.
Null is a placeholder that generally means "no data about this is available".
The use of null for this is just a convention, but a rather widespread one, to the point where some programming languages support the convention directly. The reason this convention exists has IMHO historically to do with "pointers";
many times a procedure will be defined to return a pointer to an answer, and will return what is traditionally called a Null pointer if it could not produce an answer for some reason.
Empty means (if this is a set) that it has no members. That's an explicit answer, and it is very different than "no data about this is available".
In the PHP world, apparantly uninitialized variables have the Null value, and isset on such a variable returns FALSE.
For arrays and strings, PHP follows the convention that "empty" means "has no members" although arrays and strings are not technically sets.
PHP apparantly has this funny idea that 0 and 0.0 are also "empty", by PHP design. That's abusive of the concept of "empty" IMHO: Individual numbers are not sets, so 0 can't reasonably by "empty". THis just leads to obscure programming because it violates the principle of least surprise. I'm sure the PHP designers would are that "zero is the empty number" as some kind of vague analogy; but the if analogy is vague, why bother with it? But then PHP is full of silly ideas.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
NULL is a special value which explicitly states that the variable has not been set to any value yet. Be careful with using the empty() function as you can't just determine that a variable is exactly NULL using it. For example the empty() function will return true if an int is set to 0. If you need to make sure a variable is exactly NULL use if($variable == NULL).
For more info on empty() see http://php.net/manual/en/function.empty.php
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST variable. You can check for the existence of a particular input by using isset().
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty() will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
Been awhile since i used PHP but if other languages are anything to go by empty will indicate an existing object/map/array that has no contents while null would indicate a variable that has no meaning/definition at all (uninitialised).
In database SQL, NULL means "no value".
The empty() is a nice fast way to see if the variable holds any useful info... that is for strings empty() returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()
isset() returns true if both these conditions are met:
The variable has been defined and has not yet been unset.
The variable has a non-null value in it.
A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.
$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!
From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.
empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.
This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).
Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.
In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.
I am wondering if you use unset variables, empty strings (or 0's), or "None" to determine if a variable is "None"?
The case I'm thinking of is, I'm retrieving something from the database, but find that the value is not set for the record, usually determined by the fact that there are no records or a null value. This will display to the user as "None" or "Not Set".
So the question is, when passing this value to another part of the script (ie, another function, farter on the script, template, etc), do I:
not set the variable (and therefore check if it's set in the template)
set the variable to an empty string or 0 (and check for the empty string in the template)
set the variable to "None" or "Not Set" and just echo the variable
Is there one that you usually do and why do you do it?
(I'm using PHP, so the type of the variable is somewhat unimportant.)
I'm looking for a general answer; I know that it won't always be true, but a general rule to follow.
Where possible I would normally use the nil value in the language to map to NULL.
The other options you mention all have the potential for the same ambiguity problem you'd have in the database if the value were set to empty string, None, or Not Set, when you really mean NULL.
There is also the risk of this propagating back to the database if the user can update values.
The only option that I think is something I would not do is the third option. "None" or "Not Set" really seems like a UI descriptor and not really appropriate to set as the value to be interpreted by code later.
The only exception to this would be if you have a set of known values. If they are more or less constants.
NOT_SET
NO
YES
Where NOT_SET might be the default. In this case I would still not simply echo out "not set" to the user, though.
Generally, I find it's best to handle data structures consistently throughout the program. This means leaving variables that are unset in the database unchanged when I pass them to other parts of the program. I cast or check for boundary conditions as I go if a particular function is expecting the data in a differing format.
As you said yourself, the value "None" or "Not set" is only relevant as far as displaying it to the user. For all internal use the value should be the native NULL value. The human readable values should only be substituted by whichever functions render values into the output stream
In PHP, you can set the variable to FALSE or NULL and then say:
if($var === FALSE)
...
(Notice the three equal signs)
You should explicitly set the value.
I would recommend setting it to NULL. If you're fetching the value from a database, and it's NULL (SQL) there, most likely the PHP function to grab the record will return NULL (PHP) for that field.
You can compare your string with NULL in PHP as such:
if($myString === NULL) {
/* It's NULL! */
}
If you want a certain string to show instead of NULL (which, when casted to a string, equals ""), you can set it as such:
if($myString === NULL) {
$myString = 'None';
}
Take into consideration you may need to refactor your code for internationalization later on. If you use a user string throughout your code, it will be much harder to do this.
Simply not setting a variable is bad, because you could make a typo of the variable name and wonder why when you set it "None" still shows.