I am trying to make a simple calculator using SwiftUI, but one thing frustrates me. For reference, here is the minimum reproducible example:
#State var enteredNumber: String = "" // This is the user input in a string form
#State var usable number: Int = Int(enteredNumber) // I thought this would work but it doesn't.
I found this on hackingwithswift.com, and I thought it would work. I also looked my problem up in stack overflow, but I can't seem to understand any of the questions (I'm sorta new to SwiftUI). The approach I used just gave me an error saying:
Cannot use instance member 'enteredNumber' within property initializer; property initializers run before 'self' is available
and
Value of optional type 'Int?' must be unwrapped to a value of type 'Int'
Thanks in advance for your help!
Related
I want to set data from my editText which has integer typedata. if it is string, we can make setTake, but how we can implement it at integer?
The warning is
None of the following functions can be called with the arguments supplied.
setText(CharSequence!) defined in com.google.android.material.textfield.TextInputEditText
setText(Int) defined in com.google.android.material.textfield.TextInputEditText
Your code shows data is of type UserDto. I don't know what that class looks like but it has a field called phoneNumber. This is what you are passing to setText(). I can't tell what type this phoneNumber is because you haven't shown us your UserDto class but the error tells us that it's neither an Int nor CharSequence, which it needs to be. You can try to do this maybe to make it work
binding.etPhone.setText(data.phoneNumber.toString())
I'm following along with an online course and the instructor gave this example of code...but it now throws a Null Safety error...
"The parameter 'namePerson' can't have a value of null beccause of its type..but the implicit default value is null'
void main() {
greet(greeting: 'Hey', namePerson: 'Cindy');
}
void greet({String namePerson, String greeting}){
print("$greeting $namePerson");
}
Now after researching this I found I could fix the error in three ways..by placing a ? after the word String...or by placing the word 'required' before the String...or by giving a default value...eg.
void greet({String namePerson = 'Bob', String greeting = 'Sam'}){
I don't really understand though what we should ideally do in a situation like this?
I watched a Youtube video on null safety errors'..but it is still a bit beyond my current comprehension level. Can someone explain how and why you would solve this error? Thanks for any help or tips!
You should start by asking you "In the context of my function, are my parameters required of optionnal" ?
Clearly, a function to greet someone should have :
a required, so non nullable namePerson: you must have a name to greet someone. And you cannot have a defaultValue (arbitrary "Bob" ? why ? it doesn't really make sense)
an optional greeting but with a default value, so non nullable also : you must say something to him to greet him
So I'd have it like :
void greet({required String namePerson, String greeting = 'Hello'}){
So basically, you should separate the 2 aspects :
should the inner body of my function works with a nullable or non nullable value ?
should my function take a required, optional but non nullable (so with default) value, or a totally optional one (!nullable) ?
Hope that helped
Use null check operator . Your code will run. Use the code like below. Thanks.
void main() {
greet(greeting: 'Hey', namePerson: 'Cindy');
}
void greet({String? namePerson, String? greeting}){
print("$greeting! $namePerson!");
}
I am trying to use a string ('npcName') as a variable name. So far I have tried casting dialogMap into a DynamicAccess object, but it gives me the error 'Invalid array access' when I try this:
var npcName:String = 'TestNPC';
var casted = (cast Registry.dialogMap:haxe.DynamicAccess<Dynamic>);
var tempname = casted[root.npcName[0].message];
trace(tempname);
'dialogMap' is an empty map which I want to fill like so:
Registry.dialogMap['message'] = root.npcName[0].message;
How can I use npcName, a string, in the above line of code? Is there a way to transform the string into something usable? Any help would be appreciated.
The haxe.DynamicAccess doesn't have array access (like map[key]), but is an abstract type for working with anonymous structures that are intended to hold collections of objects by the string key. It is designed to work with map.get(key) and map.set(key). It is basically a nicer wrapper around Reflect.field and Reflect.setField and does some safety checks with Reflect.hasField.
var variable = "my_key";
var value = 123;
var dynamicMap = new haxe.DynamicAccess<Dynamic>();
dynamicMap.set(variable, value);
I'm noticing you are doing very much cast and dynamic, so untyped code, which is a bit of contradiction in a typed language. What is the actual type of dialogMap?
Not sure you are aware of it but, Haxe has its own maps, which are fully typed, so you don't need casts.
var map = new Map<String, Int>();
map[variable] = value;
I think this article helps understanding how to work with dynamic (untyped) objects.
Tip; for testing such small functionalities you can doodle around on the try.haxe site : http://try.haxe.org/#4B84E
Hope this helps, otherwise here is some relevant documentation:
http://api.haxe.org/haxe/DynamicAccess.html
https://haxe.org/manual/std-reflection.html
https://haxe.org/manual/types-dynamic.html
http://code.haxe.org/category/beginner/string-variable-reflection.html
I dont know how to describe the problem, so weird. I have function like this:
long getPersonId(...){
//...
}
The above function returns Id of a person based on some arguments.
So I logged the return value of the function and it is 1.
Then I have code like this:
person = myMap.get(getPersonId(..))
which returns null object but this returns a valid Person object, why?:
person = myMap.get(1)
But as I described before getPersonId(..) returns 1, which basically means
myMap.get(getPersonId(..)) == myMap.get(1)
myMap is typed as Map<Long, Person> myMap
What is happening here?
In Groovy, as in Java, 1 is an int literal, not a long, so
myMap.get(1)
is attempting to look up the key Integer.valueOf(1), whereas
myMap.get(getPersonId(..))
is looking up the key Long.valueOf(getPersonId(...)). You need to make sure that when you populate the map you are definitely using Long keys rather than Integer ones, e.g.
myMap.put(1L, somePerson)
In your original version of this question you were calling the GORM get method on a domain class rather than the java.util.Map.get method, and that should work as required as the GORM method call converts the ID to the appropriate type for you before passing it on to Hibernate.
I am so sorry the problem was when I initialize the map myMap
Map<Long, Person> myMap = [1, new Person()]
when you say something like this the key is an integerbut not a long still groovy not complaining.
So the problem is my method was returning a long value (1L) but my actual key on the map is integer value(1).
So changing my map init to Map<Long, Person> myMap = [1L, new Person()] solved the problem.
Probably this due to dynamic nature groovy but irritating unless you know how dynamic langs behave lol.
In Groovy you can do surprising type conversions using either the as operator or the asType method. Examples include
Short s = new Integer(6) as Short
List collection = new HashSet().asType(List)
I'm surprised that I can convert from an Integer to a Short and from a Set to a List, because there is no "is a" relationship between these types, although they do share a common ancestor.
For example, the following code is equivalent to the Integer/Short example in terms of the
relationship between the types involved in the conversion
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}
def c = new Child1() as Child2
But of course this example fails. What exactly are the type conversion rules behind the as operator and the asType method?
I believe the default asType behaviour can be found in: org.codehaus.groovy.runtime.DefaultGroovyMethods.java
org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.java.
Starting from DefaultGroovyMethods it is quite easy to follow the behavior of asType for a specific object type and requested type combination.
According to what Ruben has already pointed out the end result of:
Set collection = new HashSet().asType(List)
is
Set collection = new ArrayList( new HashSet() )
The asType method recognizes you are wanting a List and being the fact HashSet is a Collection, it just uses ArrayList's constructor which takes a Collection.
As for the numbers one, it converts the Integer into a Number, then calls the shortValue method.
I didn't realize there was so much logic in converting references/values like this, my sincere gratitude to Ruben for pointing out the source, I'll be making quite a few blog posts over this topic.