How can a non-instantiated object be accessed via dot notation? (Swift Playground) - swift

I'm confused about the coordinate.column and coordinate.row used in the code swift plyground provided below. How was column and row accssed when I didn't instantiate the instance coordinate? If the for loop insatntiate coordinate, how was it instantiated when allcoordinates or world.allPossibleCoordinates are not a type? (There are no parathenthesis around world.allPossibleCoordinates...)
let allCoordinates = world.allPossibleCoordinates
var blockSet: [Coordinate] = []
//#-editable-code Tap to enter code
for coordinate in allCoordinates {
// Check for coordinates with a column > 5 OR a row < 4.
if coordinate.column > 2 && coordinate.row < 5 {
// Append coordinate to blockSet.
}
}

In Swift, the for in loop works a bit differently than a for loop in other languages. A for in loop strides over a range (I'm assuming allCoordinates is strideable). In the provided example, if the variable allCoordinates is a strideable range, the loop will go through every single item in that range assigning each value to coordinate per iteration. For more information, have a look at Apple's Documentation

Related

Why do we have to write -1 after .count in this Swift code?

In the following Swift code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
Why do we have to write -1?
I don't understand the code.
When you are using A...B, that range includes B in it. See ...(_:_:) docs. So if you say -
Int.random(in: 0...self.symbols.count-1)
It means range starts at 0 and ends at symbols.count-1 including both.
Say an array has 2 elements, it's count is 2, but valid indices are 0, 1 (2 is not a valid index), so you are just making sure that it is restricted to valid index values.
Other way to write the same would be - A..<B, in this range, B is not included. See ..<(_:_:) docs. Following is same as above.
Int.random(in: 0..<self.symbols.count)
You are using ClosedRange here. It is a range which includes both start and end value of the range. You can also used simple Range, which is open so to say. It only includes start value and not the final value.
Lets take an example.
let a = 1 ... 10 // includes all values from 1 to 10
let b = 1 ..< 10 // includes values from 1 to 9
So, basically what you are writing here,
self.numbers[2] = Int.random(in: 0 ... self.symbols.count - 1)
is equivalent to open range using,
self.numbers[2] = Int.random(in: 0 ..< self.symbols.count)
such that you dont need to add -1 to it.
Int.random can take both ClosedRange and Range, here and here.
Here are your code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
It says: your third item in numbers array will be assigned by the random item of symbols array
But how to get the random item of symbols array? You'll get it by its index.
The indexes of an array starting from 0, so, for the last element of array, its index will be the array length - 1, for example, with [1,2,3], the last element's index will be 2.
Here, you used Closed Range, it will include the last element, so if you don't minus count by one, the last index will be 3 (because array.count will return the length of the array), which is produce out of index error

How do I find the first struct where a particular member has a specific value?

Background
I have a data vector, called STRUCT_A that contains the following structs. Each of these structs have sub values that are populated from a Jenkins build at random. Below is an example of one instance of this data vector:
BEGIN STRUCT for STRUCT_A
somemember_: 4
anothermember_: 3
location_: "New York"
END STRUCT for STRUCT _A
BEGIN STRUCT for STRUCT_A
somemember_: 6
anothermember_: 123
location_: "South Bend"
END STRUCT for STRUCT_A
BEGIN STRUCT for STRUCT_A
somemember_: 10
anothermember_: 6
location_: "Baton Rouge"
END STRUCT for STRUCT_A
You can access any particular member with the following syntax: STRUCT_A.anothermember(2) will return 123 for example.
Problem and attempted solution
I want to find the very first struct where a 1 occurs in the anothermember_: member, then return the value of somemember_ in that very same struct. I have done some research on the find command, but this focuses on members of one vector. My situation deals with structs that have multiple members. Below is the closest example of what I am trying to do:
The picture above shows a 4-by-4 magic square matrix called X. What I am trying to do in the example above is find the first 2 in the matrix, which in this case is located at position five. Where this 2 is located will change each time the Jenkins build is run. The example above deals with the first half of my broader issue. However, I am not sure how to translate this method into a struct, hence my question...
Question
How do I find the first struct where a a particular member of said struct has a specific value?
A possible solution:
% Reproduction example
a = struct('somemember_',1);
b = struct('somemember_',2);
c = struct('somemember_',2);
struct_array = [a b c];
elementOfInterest = 2;
% Find index of first occurence of element of interest in the struct array
find([struct_array.somemember_] == elementOfInterest,1)
returns
2

How to compare random numbers in Swift

I’m a beginner in programming and playing around with the arc4random_uniform() function in Swift. The program I’m making so far generates a random number from 1-10 regenerated by a UIButton. However, I want the variable ’highest' that gets initialised to the random number to update if the next generated number is larger than the one currently held in it. For example the random number is 6 which is stored in highest and if the next number is 8 highest becomes 8. I don't know how to go about this. I have connected the UIButton to an IBAction function and have the following code:
var randomValue = arc4random_uniform(11) + 1
highest = Int(randomValue)
if (Int(randomValue) < highest) {
// Don’t know what to do
}
Initialise highest to 0
Every time you generate a new random number, replace the value of highest with the higher of the two numbers
highest = max(highest, randomValue)
The max() function is part of the Swift standard library and returns the larger of the two passed in vales.
edited to add
Here's a playground showing this with a bit more detail, including casting of types:
var highest: Int = 0
func random() -> Int {
let r = arc4random_uniform(10) + 1
return Int(r)
}
var randomValue = random()
highest = max(highest, randomValue)
You can see that multiple calls persist the highest value.

How do you assign a slice of numbers to an array in swift

x is an object that holds an array called point.
x implements the subscript operator so you can do things, like x[i] to get the array's ith element (of type T, which is usually an Int or Double).
This is what I want to do:
x[0...2] = [0...2]
But I get an error that says ClosedInterval<T> is not convertible to Int/Double.
Edit1:
Here is my object x:
let x = Point<Double>(dimensions:3)
For kicks and giggles: define x as [1.0,2.0,0.0]
I can get the first n elements via x[0...2].
What I want to know is how to update x[0...2] to hold [0.0, 0.0.0.0] in one fell swoop. Intuitively, I would want to do x[0...2] = [0...2]. This does not work as can be seen in the answers. I want to update x without iteration (on my end) and by hiding the fact that x is not an array (even though it is not).
[0...2] is an array with one element which, at best, will be a Range<Int> from 0 through 2. You can't assign that to a slice containing, say, Ints.
x[0...2] on the other hand is (probably) a slice, and Sliceable only defines a get subscript, not a setter. So even if the types were more compatible - that is, if you tried x[0...2] = 0...2, which at least is attempting to replace a range within x with the values of a similarly-sized collection - it still wouldn't work.
edit: as #rintaro points out, Array does support a setter subscript for ranges – so if x were a range you could do x[0...2] = Slice(0...2) – but it has to be a slice you assign, so I'd still go with replaceRange.
If what you mean is you want to replace entries 0 through 2 with some values, what you want is replaceRange, as long as your collection conforms to RangeReplaceableCollection (which, for example, Array does):
var x = [0,1,2,3,4,5]
var y = [200,300,400]
x.replaceRange(2..<5, with: y)
// x is now [0,1,200,300,400,5]
Note, the replaced range and y don't have to be the same size, the collection will expand/contract as necessary.
Also, y doesn't have to an array, it can be any kind of collection (has to be a collection though, not a sequence). So the above code could have been written as:
var x = [0,1,2,3,4,5]
var y = lazy(2...4).map { $0 * 100 }
x.replaceRange(2..<5, with: y)
edit: so, per your edit, to in-place zero out an array of any size in one go, you can do:
var x = [1.0,2.0,0.0]
// range to replace is the whole array's range,
// Repeat just generates any given value n times
x.replaceRange(indices(x), with: Repeat(count: x.count, repeatedValue: 0.0))
Adjust the range (and count of replacing entries) accordingly if you want to just zero out a subrange.
Given your example Point class, here is how you could implement this behavior assuming it's backed by an array under the hood:
struct Point<T: FloatLiteralConvertible> {
private var _vals: [T]
init(dimensions: Int) {
_vals = Array(count: dimensions, repeatedValue: 0.0)
}
mutating func replaceRange
<C : CollectionType where C.Generator.Element == T>
(subRange: Range<Array<T>.Index>, with newElements: C) {
// just forwarding on the request - you could perhaps
// do some additional validation first to ensure dimensions
// aren't being altered...
_vals.replaceRange(subRange, with: newElements)
}
}
var x = Point<Double>(dimensions:3)
x.replaceRange(0...2, with: [1.1,2.2,3.3])
You need to implement subscript(InvervalType) to handle the case of multiple assignments like this. That isn't done for you automatically.

Specman coverage: Is there a way to define ranges using variable?

I have comp_value that gets values between 1 .. 100.
In addition I have an input variable period (of the same range). I need to cover 2 ranges of comp_values: [1..period] and [period+1 .. 100]. Something like this:
cover some_event_e is {
item period using no_collect;
item comp_val using no_collect,
ranges = {
range([1..period], "Smaller_than_period");
range([period+1..100], "Bigger_than_period");
};
};
(The code causes compilation error since no variable can be written inside range).
Is there a way to collect the coverage?
Thank you for your help.
Ranges must be constant.
But if I understood your intent correctly, you can define new items like
cover some_event_e is {
item smaller_or_equal_than_period: bool = (comp_val in [1..period]) using
ignore = (not smaller_or_equal_than_period);
item greater_than_period: bool = (comp_val in [(min(100,period+1)..100]) using
ignore = (not greater_than_period);
};
Assuming period is always in [1..100].