Array cannot be inferred Error in Xcode 12 with Swift 5 - swift

Here is the simple code:
var buffer = [UInt8](_data)
var sec_ivs = [UInt8](repeating: 0, count: 8);
memcpy(&sec_ivs + 3, &buffer, 5);
The Xcode stop building the project with the following error:
How can I rewrite this code to make it works again in Xcode 12? This code is working fine in Xcode 11, but Xcode 11 did not support iOS 14 debuging.Thanks for help.

You can pass the address of the (mutable) element storage of an array to a C function with
memcpy(&sec_ivs, buffer, 5)
but that does not work with offsets. Here you need to use withUnsafeMutableBytes() to obtain a buffer pointer, so that you can add an offset:
sec_ivs.withUnsafeMutableBytes {
memcpy($0.baseAddress! + 3, buffer, 5);
}
Note that the & operator is not needed for the second argument of memcpy() because that is a constant pointer argument.
A simpler solution would an assignment to a slice of the target array:
sec_ivs[3..<8] = buffer[0..<5]

Related

memset with Swift 5.2

Sometimes I need to clear a part of a byte array to zero. With a for loop this is slow. Much faster is using the memset() function. I have the following code which will clear elements 200 to 299 of the array "a".
var a: [UInt8] = [UInt8](repeating: 1, count: 1000) // a[0..999] set to 1
start = 200
length = 100
memset(&a + start, 0, length) // a[100..199] set to 0
This worked well until Swift 5.2 with Xcode 11.4 came out. Now it works, too, but a warning appears:
Inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to '+'
How can this made, to have no warning.? Andybody has an idea?
Some more explanations is whows in Xcode:
Implicit argument conversion from '[UInt8]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to '+'
Use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope
I do not understand, what this means.
The hint to use withUnsafeMutableBytes is exactly what you should follow:
a.withUnsafeMutableBytes { ptr in
_ = memset(ptr.baseAddress! + start, 0, length)
}

I want to create a multiplication table in Swift but I am presented with the following error

I refererred to these posts:
1. Multiplication table in Swift ios
2. How do I use while loops to create a multiplication table in python?
In the second one they use a while loop but I imagine that I could use a for loop too. Could you suggest where I am going wrong in my code?
import Foundation
let i = 2
let multiplier = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for a in multiplier {
product = i * a
print("/(product)")
}
I am getting the following error when I run it in my terminal.
Error code:
no_name.swift:13:5: error: use of unresolved identifier 'product'
product = i * a
^~~~~~~
Darwin.mprotect:1:13: note: did you mean 'mprotect'?
public func mprotect(_: UnsafeMutableRawPointer!, _: Int, _: Int32) ->
Int32 ^
CoreServices.pConduit:1:12: note: did you mean 'pConduit'?
You're using a variable product which has never been declared. The compiler is trying to guess what you meant, and is suggesting some similar names for you.
I would write this as a comment but I dont have enough reputation to do so: You forgot to declare your variable, you just say product = i * a
But you have to declare it as let product = i*a
Also you can declare it out of your for loop as var product = 1 and then you can use it in your for loop as product = i*a

Why does Data.append(Mutable​Range​Replaceable​Random​Access​Slice<Data>) append slice.count bytes from the beginning of the base collection?

Using Data.append(Mutable​Range​Replaceable​Random​Access​Slice), I expected the bytes within the start/end indexes of the provided slice to be appended onto the Data instance. Instead, it appears Slice.count bytes from the beginning of the Slice.base underlying collection are appended. In contrast, instantiating Data with a slice results in the bytes between the slice's start and end indexes populating the instance.
// Swift Playground, Xcode Version 8.3 (8E162)
import Foundation
var fooData = Data()
let barData = Data([0, 1, 2, 3, 4, 5])
let slice = barData.suffix(from: 3)
fooData.append(slice) // [0, 1, 2]
Data(slice) // [3, 4, 5]
Is this the expected behavior and, if so, what might help me better understand the behavior of Data.append in this context, and its differences from Data.init?
Additionally, given that the docs for Mutable​Range​Replaceable​Random​Access​Slice encourage using slices "only for transient computation", do Data.init and Data.append reference the Slice.base collection or create their own copy of the bytes?
I've filed a JIRA issue, which is likely the best place to continue tracking a possible answer:
https://bugs.swift.org/browse/SR-4473

Swift error cannot invoke '+' with an argument list of type '($T28, $T32)'

I'm getting a strange error that I can't help but think is a compiler error. In Swift, in either a Playground or in an iOS app, if I do the following...
let array = [0, 1, 2, 3, 4, 5]
let sum = array[0] + array[1] + array[2] + array[3] + array[4] + array[5]
...I get the following compiler error.
cannot invoke '+' with an argument list of type '($T28, $T32)'
Just for grins, I changed that to an array of strings and I get the same. However, if I just add the first five values, no error. Leaving aside the fact that this is not the best way to sum up these numbers, how is this not a compiler error?
And if it isn't a compiler error, why isn't it?
if you try to create an Integer Array:
let array:[Int] = [0, 1, 2, 3, 4, 5]
I had the same issue. I guess to compiler did not recognize the type of your array values.
If you use:
let sum = Int(array[0]) + Int(array[1]) + Int(array[2]) + Int(array[3]) + Int(array[4]) + Int(array[5])
it works as expected.

Reverse Range in Swift

Is there a way to work with reverse ranges in Swift?
For example:
for i in 5...1 {
// do something
}
is an infinite loop.
In newer versions of Swift that code compiles, but at runtime gives the error:
Fatal error: Can't form Range with upperBound < lowerBound
I know I can use 1..5 instead, calculate j = 6 - i and use j as my index. I was just wondering if there was anything more legible?
Update For latest Swift 3 (still works in Swift 4)
You can use the reversed() method on a range
for i in (1...5).reversed() { print(i) } // 5 4 3 2 1
Or stride(from:through:by:) method
for i in stride(from:5,through:1,by:-1) { print(i) } // 5 4 3 2 1
stride(from:to:by:) is similar but excludes the last value
for i in stride(from:5,to:0,by:-1) { print(i) } // 5 4 3 2 1
Update For latest Swift 2
First of all, protocol extensions change how reverse is used:
for i in (1...5).reverse() { print(i) } // 5 4 3 2 1
Stride has been reworked in Xcode 7 Beta 6. The new usage is:
for i in 0.stride(to: -8, by: -2) { print(i) } // 0 -2 -4 -6
for i in 0.stride(through: -8, by: -2) { print(i) } // 0 -2 -4 -6 -8
It also works for Doubles:
for i in 0.5.stride(to:-0.1, by: -0.1) { print(i) }
Be wary of floating point compares here for the bounds.
Earlier edit for Swift 1.2: As of Xcode 6 Beta 4, by and ReverseRange don't exist anymore :[
If you are just looking to reverse a range, the reverse function is all you need:
for i in reverse(1...5) { println(i) } // prints 5,4,3,2,1
As posted by 0x7fffffff there is a new stride construct which can be used to iterate and increment by arbitrary integers. Apple also stated that floating point support is coming.
Sourced from his answer:
for x in stride(from: 0, through: -8, by: -2) {
println(x) // 0, -2, -4, -6, -8
}
for x in stride(from: 6, to: -2, by: -4) {
println(x) // 6, 2
}
There's something troubling about the asymmetry of this:
for i in (1..<5).reverse()
...as opposed to this:
for i in 1..<5 {
It means that every time I want to do a reverse range, I have to remember to put the parentheses, plus I have to write that .reverse() on the end, sticking out like a sore thumb. This is really ugly in comparison to C-style for loops, which are symmetrical counting up and counting down. So I tended to use C-style for loops instead. But in Swift 2.2, C-style for loops are going away! So I've had to scurry around replacing all my decrementing C-style for loops with this ugly .reverse() construct — wondering all the while, why on earth isn't there a reverse-range operator?
But wait! This is Swift — we're allowed to define our own operators!! Here we go:
infix operator >>> {
associativity none
precedence 135
}
func >>> <Pos : ForwardIndexType where Pos : Comparable>(end:Pos, start:Pos)
-> ReverseRandomAccessCollection<(Range<Pos>)> {
return (start..<end).reverse()
}
So now I'm allowed to say:
for i in 5>>>1 {print(i)} // 4, 3, 2, 1
This covers just the most common case that occurs in my code, but it is far and away the most common case, so it's all I need at present.
I had a kind of internal crisis coming up with the operator. I would have liked to use >.., as being the reverse of ..<, but that's not legal: you can't use a dot after a non-dot, it appears. I considered ..> but decided it was too hard to distinguish from ..<. The nice thing about >>> is that it screams at you: "down to!" (Of course you're free to come up with another operator. But my advice is: for super symmetry, define <<< to do what ..< does, and now you've got <<< and >>> which are symmetrical and easy to type.)
Swift 3 version (Xcode 8 seed 6):
infix operator >>> : RangeFormationPrecedence
func >>><Bound>(maximum: Bound, minimum: Bound) ->
ReversedRandomAccessCollection<CountableRange<Bound>>
where Bound : Comparable, Bound.Stride : Integer {
return (minimum..<maximum).reversed()
}
Swift 4 version (Xcode 9 beta 3):
infix operator >>> : RangeFormationPrecedence
func >>><Bound>(maximum: Bound, minimum: Bound)
-> ReversedRandomAccessCollection<CountableRange<Bound>>
where Bound : Comparable & Strideable {
return (minimum..<maximum).reversed()
}
Swift 4.2 version (Xcode 10 beta 1):
infix operator >>> : RangeFormationPrecedence
func >>><Bound>(maximum: Bound, minimum: Bound)
-> ReversedRandomAccessCollection<Range<Bound>>
where Bound : Strideable {
return (minimum..<maximum).reversed()
}
Swift 5 version (Xcode 10.2.1):
infix operator >>> : RangeFormationPrecedence
func >>><Bound>(maximum: Bound, minimum: Bound)
-> ReversedCollection<Range<Bound>>
where Bound : Strideable {
return (minimum..<maximum).reversed()
}
It appears that the answers to this question have changed a bit as we've progressed through the betas. As of beta 4, both the by() function and the ReversedRange type have been removed from the language. If you're looking to make a reversed range, your options are now as follows:
1: Create a forward range, and then use the reverse() function to reverse it.
for x in reverse(0 ... 4) {
println(x) // 4, 3, 2, 1, 0
}
for x in reverse(0 ..< 4) {
println(x) // 3, 2, 1, 0
}
2: Use the new stride() functions that were added in beta 4, which includes functions to specify the starting and ending indexes, as well as the amount to iterate by.
for x in stride(from: 0, through: -8, by: -2) {
println(x) // 0, -2, -4, -6, -8
}
for x in stride(from: 6, to: -2, by: -4) {
println(x) // 6, 2
}
Note that I've also included the new exclusive range operator in this post as well. .. was replaced with ..<.
Edit: From the Xcode 6 beta 5 release notes, Apple added the following suggestion for handling this:
ReverseRange has been removed; use lazy(x..
Here's an example.
for i in lazy(0...5).reverse() {
// 0, 1, 2, 3, 4, 5
}
Xcode 7, beta 2 (< Swift 3.0):
for i in (1...5).reverse() {
// do something
}
Update for Xcode 8.0+ (Swift 3.0+), per Developer Documentation, available as of 8 Dec 2020:
To iterate through a collection in reverse, without changing the collection's contents, use reversed -
let word = "Backwards"
for char in word.reversed() {
print(char, terminator: "")
}
// Prints "sdrawkcaB"
In this case, a wrapper around the collection reads the collection's contents and returns them in reverse order.
To reverse the collection's contents, use a type initializer, and provide it the collection reversed. This makes a new collection with the same contents, but reversed:
let reversedWord = String(word.reversed())
print(reversedWord)
// Prints "sdrawkcaB"
Additionally, you can use the generic function stride(from:to:by:) to return the collection's contents in reverse (as well as in its normal order):
for countdown in stride(from: 3, to: 0, by: -1) {
print("\(countdown)...")
}
// 3...
// 2...
// 1...
If the from value is higher than the to value, and the by value is negative, stride reads contents in reverse.
If the from value is lower than the to value, and the by value is positive, stride will read through the contents in their original order.
Note: Collections include arrays, sets, dictionaries, as well as other specialized collections. As long as the collection is iterable, these techniques will work.
2nd Note: as of 8 Dec 2020, Swift versions and their associated Xcode versions can be found at https://swiftly.dev/swift-versions. According to this reference, Xcode 8.0+ is associated with Swift 3.0, which is when reverse() became reversed().
Swift 3, 4+: you can do it like this:
for i in sequence(first: 10, next: {$0 - 1}) {
guard i >= 0 else {
break
}
print(i)
}
result: 10, 9, 8 ... 0
You can customise it any way you like. For more info read func sequence<T> reference
This could be another way of doing this.
(1...5).reversed().forEach { print($0) }
Reverse() function is used for reverse number.
Var n:Int // Enter number
For i in 1...n.reverse()
{
Print(i)
}