My query is the following:
$users = User::where("admin", <>, '1')->where('id', <>, $my_id)->get();
The error is the following:
Sintax error
unexpected: !=
after ','
expected: exit, integer, double, identificer, STRING, VARNAME, variable, String, String, clone, function, isset, empty, list, array, _CLASS, _METHOD, _FUNCTION, _NAMESPACE, _DIR_, ª, define, include, include_once, eval, require, require_once
POSSIBLE Syntax Error (check preceding valid syntax error)
unexpected: !=
POSSIBLE Syntax Error (check preceding valid syntax error)
unexpected: )
Introduce Variable
-----
(Alt-Enter shows hints)
I unknowed the error. Someone could help me. thank you!
expect exit, integer, double, identifier, STRING_VARNAME
Because you can't just pass <> or != it has to be a string!
$users = User::where("admin", "<>", '1')->where('id', "<>", $my_id)->get();
Related
I'm trying to write a simple abstract class in F# with some basic parameter validation:
[<AbstractClass>]
type Record(recordType: int16) =
let recordType: int16 = recordType
do
if recordType < 0s then
invalidArg (nameof recordType)
However, I'm getting an error on the last line: 'this if expression is missing an else branch.' I tried adding an else branch that just evaluates to null, but then the type system doesn't agree with my code. Am I doing something wrong? Should I be validating my arguments using some other method?
The problem is that invalidArg requires a parameter name (which you've passed as nameof recordType as well as an error message, which you left off, and your if branch returns a function (string -> 'a as the return type is unknown/unreachable since the exception is thrown).
If you look at the docs for invalidArg, you see this: invalidArg parameter-name error-message-string. Your code is effectively like this:
// This is a function: string -> 'a (as it raises an exception, the return type is unknown)
let partialInvalidArg = invalidArg (nameof recordType)
if recordType < 0s then
partialInvalidArg // You're returning a function, not unit, so the compiler complains
If you include the error message, the function is actually called in the branch, and this will compile fine:
[<AbstractClass>]
type Record(recordType: int16) =
let recordType: int16 = recordType
do
if recordType < 0s then
invalidArg (nameof recordType) "The recordType must be greater or equal to zero"
Simple question for you folks about unwrapping optionals.
I've read and seen the multiple examples of unwrapping like the following
var strArray: [String]?
strArray = ["John", "Stacy", "Stephanie" ]
if let forSureNames = strArray{
for name in forSureNames{
print("\(name)")
}
} else{
print("Failed unwrapping")
}
However, My question is for if let forSureNames = strArray{...
When typing syntax similar to C++ (and from some swift examples), adding parenthesis
if (let forSureNames = strArray){
Gives the error codes:
'()' is not convertible to 'Bool'
error: MyPlayground.playground:13:4: error: expected expression in list of expressions
if(let forSureName = strArrays){
^
error: MyPlayground.playground:13:4: error: expected '{' after 'if' condition
if(let forSureName = strArrays){
^
Can anyone help explain the difference?
Edit
First time I asked a question on Stack overflow and feedback is awesome. I was trying to use a similar coding style to C++ due to my familiarity for an easy transition. However, you guys made it clear that it’s an incorrect approach. Thank you for a new and technical perspective towards unwrapping. Cheers!
As you know, () can be used to surround an expression and it will have no effect on the evaluation of that expression, and you are asking "why can't I do the same to let forSureNames = strArray?" Right?
This is because let forSureNames = strArray is not an expression. You are parsing this statement wrong. The word let is part of the if let statement.
You are confusing if let statements with C-style if statements, where after the if, there is always an expression that evaluates to Bool. if let simply does not work like that. It takes the form:
if let <identifier> = <expression> { }
where expression must evaluate to an optional type. So putting () around let <identifier> = <expression> makes little sense. You could put () around strArray because that is an expression, but I don't see the point of that.
if (let forSureNames = strArray) {
... this is trying to use optional binding. Optional binding allows you to safely unwrap some optional constant/variable which can be nil. If this value is assigned, it satisfies the if statement with this unwrapped (non-optional) constant/variable.
But, it doesn't work with parentheses, since values coming from parentheses have to be of type Bool. An optional binding doesn't return a Bool value directly, it just attempts to assign the constant/variable and implicitly returns a boolean based on whether the assignment occurred.
if (true) {...} // works
if (let value = optional) {...} // doesn't work
So, you have to remove these parentheses
if let forSureNames = strArray {...}
Unlike other languages, conditions in Swift don't have to be inside parentheses and it is recommended not to use them if they aren't required.
Swift is vastly different from C++, so you shouldn't be surprised that C++ syntax doesn't work in Swift.
There are two type of if statements in Swift: the type that takes an expression (if foo.bar), and the type that does pattern matching (if let foo = bar, if case .some(let foo) = bar, etc).
Because Swift supports parenthesized expressions, if foo.bar works the same as if (foo.bar): in the first case, the condition is foo.bar, and in the second case, the condition is (foo.bar). In other words, the parentheses here are part of the condition expression, not part of the if statement. This contrasts with C++, where the parentheses are part of the if statement. In both cases, however, you can add as many parentheses as you want: if (((((((((foo.bar))))))))), though silly, is superficially valid in both languages.
Recall that you can wrap arbitrary expressions in parentheses, but you can't just wrap anything in parentheses. You wouldn't write (if foo.bar) in Swift or C++, because you know that if isn't an expression. Then, the same applies to let foo = bar. It's not an expression either, so you can't wrap it in parentheses. if let foo = bar is fine, but if (let foo = bar) isn't.
C++ supports a similar syntax in some cases:
if (auto foo = make_unique<int>(3)) { ... } else { ... }
This syntax declares foo and tests it (using its operator bool()), and then branches the program appropriately. Since the condition is a declaration statement, not an expression, it can't be wrapped in more parentheses either: if ((auto foo = make_unique<int>(3))) is a compile-time error, just like if (let foo = bar) in Swift.
Can anyone help explain the difference?
The difference is that Swift is not C++. Although they are similar in many ways, they have different grammars. The grammar defines (in part) the language's syntax.
In C++, an if statement is part of the selection-statement production in the grammar:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
So the parentheses around the condition of the if statement are part of the if statement, and not part of the condition.
In Swift, an if statement is the only production of the if-statement production in the grammar:
if-statement → if condition-list code-block else-clauseopt
Note that there are no parentheses directly in the if-statement's production. So if there are to be parentheses, they must be part of the condition-list production. Here's how condition-list is defined:
condition-list → condition | condition , condition-list
condition → expression | availability-condition | case-condition | optional-binding-condition
So a condition-list is one or more conditions, separated by commas. If you click through each of the four alternatives in condition, you'll find that availability-condition must start with the token #availability, case-condition must start with the token case, and optional-binding-condition must start with either the token let or the token var. None of those three productions can start with a parenthesis token.
The only production of condition that can start with the token ( is the expression production, and an expression production cannot have the token let after the token (.
My code is:
func getTimeStamps( tablename : String) -> String {
let time_stamps = db["time_stamps"]
let t_tabelle = Expression<String?>["tabelle"]
let t_time_stamp = Expression<String?>["TIME_StAMP"]
let query = time_stamps.filter(like(tablename, t_tabelle))
return query[t_time_stamp]
}
But I get an error on conversion:
Expression<String?> is not convertible to String
How can I return a String?
Thanks
Hauke
The error refers to the fact that your function signature for getTimeStamps, String -> String, has return type String, but the value you're returning, query[t_time_stamp], is an Expression<String?>.
Query structures can be subscripted with Expressions to return a namespaced version of the expression:
let id = Expression<Int64>("id") // literally: "id"
let users = db["users"]
let users_id = users[id] // literally: "users"."id"
In your case, subscripting query with t_time_stamp is merely returning a new, namespaced version of the t_time_stamp expression (in your version, "time_stamps"."TIME_StAMP"). This is helpful for disambiguation, but unlikely your intent.
It's tough to tell from the code provided exactly what you want to return from the function, but it looks like you want to execute the query in order to extract a value. Row structures, once fetched, can be subscripted with expressions to retrieve the underlying value.
If you're looking to retrieve a single row, try the following:
if let row = time_stamps.filter(like(tablename, t_tabelle)).first {
return row[t_time_stamp]
}
Your function, however, still returns String, not String?. If it's ever possible for your query to return zero rows or for any of the rows it does return to have a NULL timestamp column, you need to handle your optionals accordingly.
If, however, a NULL timestamp would indicate a programming error/bug, you should update String? to String accordingly:
let t_time_stamp = Expression<String>["TIME_StAMP"]
// ...
return query.first![t_time_stamp]
Please note that the above will crash if you're mishandling the potential for optional values.
When I create output of JSON using Alamofire, I saw this in my console
What does Optional({}) mean?
Optional({
0 = (
All,
""
);
C2001 = (
"ARAI Bay Side"
);
C2002 = (
"ARAI Fukuoka"
);
})
I am newbie to swift and this, so any ideas?
What Alamofire gives you is an optional variable, because it can't predict in advance whether the request will succeed and have output or fail and have none.
Similarly, it also gives you an error? variable (note the ?, which means it's also an optional) that will be nil if the request succeeded or will be something (most likely an NSError) if an error occurred.
You can check with if yourVariable != nil to see whether the optional variable is set (contains something), in which case you'll be able to unwrap it with yourVariable!.
You can also use the following :
if let yourUnwrappedVariable = yourVariable!
to unwrap the variable into a new (non-optional) yourUnwrappedVariable variable and execute the code in that if block if the variable was set (contained something, wasn't nil), this time without needing to unwrap the variable again like the previous example (here you already have the yourUnwrappedVariable variable and can use it right away in that if block).
Finally, if you're sure the variable will always be set, you can unwrap it by passing it followed by a ! sign to whatever method call you want like so :
myMethod(initWithData: yourVariable!, anotherArgument: anotherValue)
If the variable ever happens to not contain anything, an exception will be thrown.
What you are seeing is the output from global functions like print() or println(), which enclose optional descriptions inside Optional( ), unless the value of the optional is nil, in which case just nil is printed.
If you have this:
var foo: Int?
foo = 7
println(foo)
The output is Optional(7)
whereas
println(foo!)
just prints 7
I have a model with a column entry, which is a String. Sometimes entry has some text in it, sometimes it doesn't and it's an empty string.
When I try to print the string in console, I'm getting The process has been returned to the state before expression evaluation. (running e object.entry)
Not sure why it isn't just printing ""
Trying e object.entry! gives me error: operand of postfix '!' should have optional type; type is 'String'
Any ideas on how to fix this?
Empty String "" doesn't mean nil, and entry is not an optional type.
I think you are supposed to declare entry as "" when initialize the object
class object {
var entry = ""
//do anything you want next
}