How to define an array with a single element in it? - arrays

I am trying to define an array with single element... so,
var arr:Array = new Array(1,2,3,4) // arr[0] = 1
// but
var arr:Array = new Array(1) // arr[0] = undefined
//Also,
var arr:Array = new Array([1]) // arr[0] = 1 , << ILLUSION
//Because, arr[0] is NOT A NUMBER, IT ITSELF IS OF TYPE=> ARRAY.
var arr:Array = [1] //arr[0]=1 but i think it's AS1.0 notation..
So, is their any AS3.0 way of defining array with single element ?

var arr:Array = [1]; //arr[0]=1 but i think it's AS1.0 notation..
Why? This is perfectly legal shorthand array initialization, and it's exactly the way to do it.

Lol, I remember dealing with this a year or 2 back, the way I did it was with 2 lines.
var arr:Array = new Array();
arr[0] = "the element";
This is because the constructor for Array accepts the size of the array as an argument if you are passing a single integer value. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#Array()

weltraumpirat is right only in that the code will compile, it's still actionscript 1/2 notation (AVM1). You said you want to know the "AS3 way".... and one major difference and benefit of AS3 (AVM2) over AS1/AS2 (AVM1) is strict typing. Hence the creation of the Vector object, aka a strictly typed array (and it's faster because of that strict typing). Here is the proper way to initialize a typed array with 1 or more defined objects:
var vector:Vector.<String> = Vector.<String>(["v1", "v2", "v3"]);
See more here:
http://www.daveoncode.com/2009/04/06/actionscript-vector-class-initialization-with-a-source-array/
Edit For all the people who don't know what they're talking about:
http://www.mikechambers.com/blog/2008/09/24/actioscript-3-vector-array-performance-comparison/
Simple test, vector == 40% faster than array
http://www.masonchang.com/blog/2011/4/21/tamarin-on-llvm-more-numbers.html
Summary of tamarin JIT tests, typed variables performing 20% or more faster than un-typed in every scenario.
For the people who REALLY don't know what they're talking about, Tamarin IS the flash virtual machine (at least the open source component, the core minus the UI and other things).
Edit... again.. sigh
For people who do not understand what "context" is... when I say that the vector is FASTER... I'm speaking of the overall performance of the object in the virtual machine. This is not my own claim, it comes from adobe themselves and there are benchmarks from a flash platform evangelist included in my answer ( or rather a link to ). Maybe the people who are arguing with me don't have English as their first language.....

var myArray:Array = new Array();
myArray.push(1);
trace(myArray[0]); //1

Related

Error when trying to set array in userdefaults: Thread 1: "Attempt to insert non-property list object

I have solved the issue now, thanks for your help. I shouldn't have tried to save arrays with UITextViews, but I should have saved their text as strings instead. Here was the original question:
I have tried a lot, and googled a lot, but I can't solve this problem on my own. Whenever I try to save an array in userdefaults, it just is not working. I get the following error:
Thread 1: "Attempt to insert non-property list object (\n "<UITextView: 0x14001f800; frame = (0 0; 355 180); text = 'D'; clipsToBounds = YES; gestureRecognizers = <NSArray: 0x600003f01d10>; layer = <CALayer: 0x6000031c83e0>; contentOffset: {0, 0}; contentSize: {355, 30}; adjustedContentInset: {0, 0, 0, 0}>"\n) for key content"
I don't know what a non-property list object is. And I do not know how to solve the problem. Below is the lines of code that do not work.
var contentList: [Any] = []
let cl = defaults.array(forKey: "content")!
if cl.count != 0{
contentList += cl
}
contentList.append(label)
defaults.setValue(contentList, forKey: "content")
If I take out the last line of code by turning it into a comment everything runs just fine. How should I replace that line of code? I essentially want to save an array of UITextViews and make it larger every time I call a fucntion (this code is part of a larger function). The reason why I have created another two lists (cl and contentList) is that it helps me with a problem down the line. What I cannot understand however, is why the last line of code doesn't work. If anyone has any ideas, please help me, it would be much appreciated.
Use only String as stated in comments :
var contentList: [String] = []
let cl = defaults.array(forKey: "content")!
if cl.count != 0{
contentList += cl
}
If lbText = label.text {
contentList.append(lbText)
defaults.setValue(contentList, forKey: "content")
}
You can only store a very limited list of data types into UserDefaults, commonly referred to as "property list objects" (Since property list (or plist) files will only store the same data types.
To quote the Xcode docs on UserDefaults, in the section titled "Storing Default Objects":
A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary [or Data, String, NSNumber, Date, Array, or Dictionary types in Swift.] If you want to store any other type of object, you should typically archive it to create an instance of Data.
(I added the equivalent Swift types to the above quote in square brackets, since it looks like Apple hasn't updated it for Swift.)
That's worded a little awkwardly. The idea is that you can only store data of the types listed. Because the Array and Dictionary types are "container" types, you can store any combination of arrays and dictionaries that contain combinations of any of the above types. For example, you can store an array that contains a dictionary, 3 dates, 2 floats, a Double, some Data, and 2 arrays, and those dictionaries and arrays can contain other dictionaries and/or arrays.)
It is almost always wrong to archive UIView objects like UITextViews. You should save the text properties of your text views instead.
If you want to manage a vertical stack of UITextView objects, I suggest adding a vertical stack view to your user interface, and then writing code that adds or removes UITextView subviews to your stack view. You should be able to find plenty of examples of adding and removing objects from stack views online. (It's really easy.)
If you want to manage a scrolling list of feeds of arbitrary length, you might want to use a table view or collection view instead. Those require that you set up a data model and implement a "data source". That takes a little practice to get right, but is very powerful.

In Perl 6, can I use an Array as a Hash key?

In the Hash documentation, the section on Object keys seems to imply that you can use any type as a Hash key as long as you indicate but I am having trouble when trying to use an array as the key:
> my %h{Array};
{}
> %h{[1,2]} = [3,4];
Type check failed in binding to parameter 'key'; expected Array but got Int (1)
in block <unit> at <unknown file> line 1
Is it possible to do this?
The [1,2] inside the %h{[1,2]} = [3,4] is interpreted as a slice. So it tries to assign %h{1} and %{2}. And since the key must be an Array, that does not typecheck well. Which is what the error message is telling you.
If you itemize the array, it "does" work:
my %h{Array};
%h{ $[1,2] } = [3,4];
say %h.perl; # (my Any %{Array} = ([1, 2]) => $[3, 4])
However, that probably does not get what you want, because:
say %h{ $[1,2] }; # (Any)
That's because object hashes use the value of the .WHICH method as the key in the underlying array.
say [1,2].WHICH; say [1,2].WHICH;
# Array|140324137953800
# Array|140324137962312
Note that the .WHICH values for those seemingly identical arrays are different.
That's because Arrays are mutable. As Lists can be, so that's not really going to work.
So what are you trying to achieve? If the order of the values in the array is not important, you can probably use Sets as keys:
say [1,2].Set.WHICH; say [1,2].Set.WHICH
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
# Set|AEA2F4CA275C3FE01D5709F416F895F283302FA2
Note that these two .WHICHes are the same. So you could maybe write this as:
my %h{Set};
dd %h{ (1,2).Set } = (3,4); # $(3, 4)
dd %h; # (my Any %{Set} = ((2,1).Set) => $(3, 4))
Hope this clarifies things. More info at: https://docs.raku.org/routine/WHICH
If you are really only interested in use of an Object Hash for some reason, refer to Liz's answer here and especially the answers to, and comments on, a similar earlier question.
The (final1) focus of this answer is a simple way to use an Array like [1,'abc',[3/4,Mu,["more",5e6],9.9],"It's {<sunny rainy>.pick} today"] as a regular string hash key.
The basic principle is use of .perl to approximate an immutable "value type" array until such time as there is a canonical immutable Positional type with a more robust value type .WHICH.
A simple way to use an array as a hash key
my %hash;
%hash{ [1,2,3].perl } = 'foo';
say %hash{ [1,2,3].perl }; # displays 'foo'
.perl converts its argument to a string of Perl 6 code that's a literal version of that argument.
say [1,2,3].perl; # displays '[1, 2, 3]'
Note how spaces have been added but that doesn't matter.
This isn't a perfect solution. You'll obviously get broken results if you mutate the array between key accesses. Less obviously you'll get broken results corresponding to any limitations or bugs in .perl:
say [my %foo{Array},42].perl; # displays '[(my Any %{Array}), 42]'
1 This is, hopefully, the end of my final final answer to your question. See my earlier 10th (!!) version of this answer for discussion of the alternative of using prefix ~ to achieve a more limited but similar effect and/or to try make some sense of my exchange with Liz in the comments below.

Is it possible to apply changes to all objects in Array without using "for each" or "for" in Swift 3?

for example
var imageViewArray:UIImageView = [imageView1,imageView2,imageView3]
I want to chage sameimageView.image = img or imageView.isUserInteractionEnabled = false to all Image View inside the array
1. It's an array
First of all it's not
var imageViewArray:UIImageView
but
var imageViewArray:[UIImageView]
because you want an array of UIImageView right?
2. Naming conventions
Secondly is Swift we don't name a variable after it's type so imageViewArray becomes imageViews.
3. map
Now if you really hate the for in and the foreach your can write
imageViews = imageViews.map { imageView in
imageView.isUserInteractionEnabled = true
return imageView
}
or as suggested by Bohdan Ivanov in the comments
imageViews.map { $0.isUserInteractionEnabled = true }
4. Wrap up
This answer shows you how to use the wrong construct (map) to do something that should be made with the right construct (for in).
That's the point of having several constructs, everything could be made with an IF THEN and a GOTO. But a good code uses the construct that best fits that specific scenario.
So, the best solution for this scenario is absolutely the for in or the for each
imageViews.forEach { $0.isUserInteractionEnabled = true }

setting object properties value for object array in matlab

I have created an array of objects and I would like assign a property value in a vector operation without using a for loop. Unfortunately I get an error.
A simplified example of the problem.
classdef clsMyClass < handle
properties
dblMyProperty1
end
methods
function obj = clsMyClass()
end
end
end
And when running
vecMyArray = clsMyClass.empty(100,0);
vecMyArray(100) = clsMyClass;
vecMyArray.dblMyProperty1 = 1:100;
We get the following error:
??? Incorrect number of right hand side elements in dot name
assignment. Missing [] around left hand side is a likely cause.
Any help would be appreciated.
I see what you're trying to do now. Use disperse from the MATLAB File Exchange:
>> [vecMyArray.dblMyProperty1] = disperse(1:100);
>> vecMyArray(1).dblMyProperty1
ans =
1
>> vecMyArray(10).dblMyProperty1
ans =
10
You can use the deal function for exactly this purpose:
[vecMyArray.dblMyProperty1] = deal(1:100);
See: http://www.mathworks.com/company/newsletters/articles/whats-the-big-deal.html
Edit: No you can't, actually; that'll set them to all be the vector 1:100.
I think you'll find your answer here in "Struct array errors." Even though this is a class, similar rules apply.
Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:
So you'll need:
for ii=1:100
vecMyArray(ii).dblMyProperty1 = ii;
end
I know it's not satisfying, but I think it at least helps us to definitively understand this error.

Go: Define multidimensional array with existing array's type and values?

Is it possible to a)define b)initialize a new multidimensional array using an existing array, like in following code instead of var b [2][3]int, just saying something like var b [2]a ?
Using a's type whatever it is, instead of hardcoding it (which misses the point of using [...] for a).
And perhaps handling initialization=copying of values at the same time?
package main
func main () {
a := [...]int{4,5,6}
var b [2][3]int
b[0],b[1] = a,a
}
(I'm aware of ease and convenience of slices, but this question is about understanding arrays.)
Edit: can't believe I forgot about var b [2][len(a)]int, beginner's brain freeze. One line answer would be var b = [2][len(a)]int{a,a} . That's a type conversion, right?
The following code would also work. Both your example and mine do the same thing and neither should be much faster than the other.
Unless you use reflect to make a slice (not array) of your [3]int, it is impossible to not repeat [3]int in your new type. Even that is not possible in the current release. It is in tip and will be released in Go 1.1.
package main
import "fmt"
func main() {
a := [...]int{4,5,6}
var b = [2][3]int{a, a}
fmt.Println(b)
}

Resources