How do i use joined() function after using sorted() in swift? - swift

let var1 = "AnyCode".sorted()
print(var1.joined(separator:""))
ERROR: No exact matches in call to instance method 'joined'
I am trying to join the array after sorting the string. = "AnyCode"
I was expecting the output was = ACdenoy
But it is giving an error.

A Swift String is a collection of Characters, and sorted() applied to a collection returns an array with the collection elements in sorted order.
So var1 has the type [Character], and you can simply create a new string from that array with:
let var1 = "AnyCode".sorted()
print(String(var1)) // ACdenoy

Alternatively to Martin R's answer (but not better than that answer), you might have said
print(var1.map(String.init).joined())
...turning the characters to strings before trying to join the array elements.

Related

Why result of reversed() does behave itself like being an Array? [duplicate]

I'm wondering about the reversed() method on a swift Array:
var items = ["a", "b", "c"]
items = items.reversed()
the signature of the reversed method from the Apple doc says that it returns a
ReversedRandomAccessCollection<Array<Element>>
could that be assigned back to items without doing what the apple doc say which is
For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.
or would it give problem in the future? (since the compiler doesn't complain)
There are 3 overloads of reversed() for an Array in Swift 3:
Treating the Array as a RandomAccessCollection,func reversed() -> ReversedRandomAccessCollection<Self> (O(1))
Treating the Array as a BidirectionalCollection,func reversed() -> ReversedCollection<Self> (O(1))
Treating the Array as a Sequence,func reversed() -> [Self.Iterator.Element] (O(n))
By default, reversed() pick the RandomAccessCollection's overload and return a ReversedRandomAccessCollection. However, when you write
items = items.reversed()
you are forcing the RHS to return a type convertible to the LHS ([String]). Thus, only the 3rd overload that returns an array will be chosen.
That overload will copy the whole sequence (thus O(n)), so there is no problem overwriting the original array.
Instead of items = items.reversed(), which creates a copy of the array, reverse that and copy it back, you could reach the same effect using the mutating function items.reverse(), which does the reversion in-place without copying the array twice.

Gets elements from 3 dimensional array

I'm new in Swift and do not know everything , i have this kind of an array
var arrayOFJumpForwardBack: [Int: [String: [String]]] =
[1: ["chapter": ["15 sec","30 sec","45 sec","60 sec"]]]
and , i'd like to know how can i get certain elements from this array?
Swift - Arrays & Dictionaries
The syntax of an array is as follows:
["value1","value2","value3"]
The syntax of a dictionary is as follows:
["ABC":"valueForABC","XYZ":"valueForXYZ"]
In this case you're using a dictionary, and the main difference with the array is that the order doesn't matter, each value is represented with a key, so with the following example:
Example:
Let's say we have a dictionary where we have stored the word "apple" whose key is "JHC" and "pear" whose key is "IOP". We want to print "I have an apple", then:
var myFridge:[String:String] = ["JHC":"apple","IOP":"pear"]
print("I have an \(myFridge["JHC"]!)")
A multidimensional array is just an array inside of another, x dimensions you want.
I'd rather prever to create a dictionary as above ↑

Create a fixed size 3 dimensional array of type string

I am trying to create a fixed size 3 dimensional array in Swift with datatype of string like this:
var 3dArray:[[[String]]] = [[[50]],[[50]],[[50]]]
But it is giving error:
Cannot convert value of type 'Int' to expected element type string
From your question title you are trying to create 3d array with datatype [[[String]]] and in your question detail you are assigning it an Int value which is not possible in swift. That's why you are getting an error. Because your 3dArray object is expecting a String values
Either you can assign String values this way:
var yourArr: [[[String]]] = [[["50"]],[["50"]],[["50"]]]
Or if you want to make Int array you can do it this way:
var yourArr: [[[Int]]] = [[[50]],[[50]],[[50]]]
Note:
As #Martin R suggested variable names cannot start with a digit.
There is no typical way of creating multidimensional arrays in Swift.
But, you can create an array which will contain only String arrays and then append 3 different String arrays. Please find the code below:
var array = [[String]]()
array.append([String]())
array.append([String]())
array.append([String]())
At the end your array will be looking this way:
[[], [], []]
Or you can just create same array this way:
var array:[[String]] = [["50"],["50"],["50"]]
But keep in mind, "50" are strings which are content of those arrays and not their size.
If you want to have a fixed-size array, then you have to use some third party solutions like this one.

Scala create array of empty arrays

I am trying to create an array where each element is an empty array.
I have tried this:
var result = Array.fill[Array[Int]](Array.empty[Int])
After looking here How to create and use a multi-dimensional array in Scala?, I also tried this:
var result = Array.ofDim[Array[Int]](Array.empty[Int])
However, none of these work.
How can I create an array of empty arrays?
You are misunderstanding Array.ofDim here. It creates a multidimensional array given the dimensions and the type of value to hold.
To create an array of 100 arrays, each of which is empty (0 elements) and would hold Ints, you need only to specify those dimensions as parameters to the ofDim function.
val result = Array.ofDim[Int](100, 0)
Array.fill takes two params: The first is the length, the second the value to fill the array with, more precisely the second parameter is an element computation that will be invoked multiple times to obtain the array elements (Thanks to #alexey-romanov for pointing this out). However, in your case it results always in the same value, the empty array.
Array.fill[Array[Int]](length)(Array.empty)
Consider also Array.tabulate as follows,
val result = Array.tabulate(100)(_ => Array[Int]())
where the lambda function is applied 100 times and for each it delivers an empty array.

Iterating Over Unique Values in Matlab

I've been trying to follow this answer in order to obtain unique strings from a given cell array. However, I'm running into trouble when iterating over these values. I have tried for loops as follows:
[unique_words, ~, occurrences] = unique(words);
unique_counts = hist(occurrences, 1:max(occurrences));
for a=1:numel(unique_words)
word = unique_words{a}
count = unique_counts{a}
result = result + a_struct.(unique_words{a}) + unique_counts{a}
end
When trying to reference the items like this, I receive the error:
Cell contents reference from a non-cell array object.
Changing the curly brackets to round brackets for unique_couts yields the error:
Reference to non-existent field 'N1'.
Changing both unique_words and unique_counts to round brackets yields:
Argument to dynamic structure reference must evaluate to a valid field name.
How am I to iterate over the results of unique?
unique_words is a cell array. unique_counts is a vector. So unique_words should be accessed using curly brackets and unique_counts using round ones. The error that you are getting in this case is related to the a_struct (which is not defined in the question) not having the corresponding field, not the access method.