Generic parameter 'D' could not be inferred [Swift] - swift

import CryptoKit
func getAlgorithm(algo: String) {
var algorithms = ["md5":Insecure.MD5.hash,
"sha1":Insecure.SHA1.hash,
"sha256":SHA256.hash,
"sha384":SHA384.hash,
"sha512":SHA512.hash]
return algorithms[algo]
}
var algorithm: () = getAlgorithm(algo: "sha256")
link to screenshot
The error: "Generic parameter 'D' could not be inferred" is happening on line 4, I am not really familiar with generics. That's why I'm asking this question here. Could any of you please explain what's wrong with this code? That would be greatly appreciated.
I wan't to be able to specify a hashing algorithm and use it multiple times instead of having to do a switch statement and having to call the function there. (For efficiency reasons)

Related

Swift method needs to sort a polymorphic collection of UInt32

Confused (and a little frustrated) with Swift5 at the moment.
I have a method:
func oidsMany(_ oids:Array<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
Discovered I have a case where I want to pass a Set to this method just as well. Either way, I'm going to sort an Array or a Set to an Array right away.
Waded through the many many many protocols that both Set and Array conform to, noticed that they both conform to [Sequence][1] and that Sequence responds to sorted. Perfect.
But when I change the above to:
func oidsMany(_ Sequence<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
I get the following error hints:
Cannot specialize non-generic type 'Sequence'
Member 'sorted' cannot be used on value of protocol type 'Sequence'; use a generic constraint instead
What's the right way to approach this? I could just add a second oidsMany(_ Set...) that casts its arg as an array and recalls. But I feel like I'm missing something fundamental here. My experience from other languages is not mapping over well here.
You can as the error message suggest use it as a generic constraint instead
func oidsMany2<Sortable: Sequence>(_ oids: Sortable) -> MCCommandBuilder where Sortable.Element: Comparable {
let sorted_oids:[Sortable.Element] = oids.sorted()
//...
}
if you only want to accept collections where the element is UInt32 you can change the where condition to
where Sortable.Element == UInt32

calling pcap_loop from Swift 3

I was trying this code from https://github.com/dfrencham/swiftPCap
pcap_loop(pcapSession, numberOfPackets,
{
(args: UnsafeMutablePointer<u_char>,
pkthdr:UnsafePointer<pcap_pkthdr>,
packet: UnsafePointer<u_char>) ->Void in
// lets handle the result using a call to a singleton
// we can keep state this way, and not have to
// tool around by passing pointers to UnsafePointers
// and dereferencing later
let pa = PacketAnalyser.sharedInstance
pa.Process()
},
nil)
Now it is Swift 3, I cannot compile with the following errors
cannot convert value of type '(UnsafeMutablePointer, UnsafePointer, UnsafePointer) -> Void' to expected argument type 'pcap_handler!'
Not really sure how to proceed, pretty much a newbie at referencing C code from Swift. I have read the documentation, but not having much luck.
Thanks

Possible in swift to do a recursive function call with javascriptcore?

I have a function that is called by javascript with JavascriptCore.
Now inside that function I have to evaluate a javascript again under a certain condition. This should call the same function.
let My_JS_Function: #convention(block) ( String, String, String ) -> ( ) = {
thing_1, thing_2, thing_3
in
let my_Condition = true
if my_Condition {
let c = JSContext()
// compiling error: "Variable used within its own initial value"
Context.setObject(unsafeBitCast(My_JS_Function, AnyObject.self), forKeyedSubscript: "My_JS_Function")
c.evaluateScript("My_JS_Function("value 1","value 2","value 3");")
}
}
Now XCode tells me:
Variable used within its own initial value
Does anybody know wheather there's a way how to solve this problem?
Maybe a way to write the My_JS_Function as a function and not like here as a variable?
I could fix the problem with avoiding having functions as properties.
Therefor I put the functionality in an extra class and used JSExport.
One example for how it can be done with JSExport can be found here.

Recasting 'UnsafePointer<Void>' to 'CFHTTPMessageRef'

I've tried dozens of things to get this right and just can't come up with anything that works. Can anyone tell me what's wrong with the following Swift code:
let incomingRequest: CFHTTPMessageRef? = CFDictionaryGetValue(self.incomingRequests as CFMutableDictionaryRef, unsafeAddressOf(incomingFileHandle!)) as CFHTTPMessageRef
The code above gives the error message: 'UnsafePointer<Void>' is not convertible to 'CFHTTPMessageRef'
I guess what I don't understand is how do I convert an 'UnsafePointer' returned by a Core Foundation function to the pointer type it should be (i.e. CFHTTPMessageRef in this case). How do I find documentation on how to do this. I've read everything I can find, but nothing so far explains how to recast return values to what they should have been in the first place. This has to be documented somewhere, doesn't it?
EDIT
Here's the code I'm having trouble with:
let incomingRequest = CFDictionaryGetValue(self.incomingRequests as CFMutableDictionaryRef, unsafeAddressOf(incomingFileHandle!))
unsafeBitCast(incomingRequest, CFHTTPMessageRef.self)
if (incomingRequest != nil) {
let success: Boolean = CFHTTPMessageAppendBytes(incomingRequest as CFHTTPMessageRef, unsafeAddressOf(data!.bytes) as UnsafePointer<UInt8>, data!.length)
if success { // Do something... }
The CFHTTPMessageAppendBytes call still gives a "Type 'UnsafePointer' does not conform to protocol 'AnyObject'". And the following 'if' check for 'success' complains that "Type 'Boolean' doesn not conform to protocol 'BooleanType'". What the heck is that about? Boolean isn't a Boolean type?
I find the strict type checking of Swift extremely frustrating. So far it is far more difficult to code in than Obj-C, C, or any of the other languages I've used. I'm sure it's because I just don't get it, or haven't found the right documentation, but this is really driving me crazy.
Use unsafeBitCast. As following example:
import Foundation
var x = "1"
var dict : NSMutableDictionary = [x: "2"]
var y = CFDictionaryGetValue(dict as CFMutableDictionaryRef, unsafeAddressOf(x))
let str: NSString = unsafeBitCast(y, NSString.self)
str == "2"
FYI: There is one quora related with unsafeBitCast. http://www.quora.com/Why-does-Swift-not-allow-implicit-type-conversion

Unable to figure out the usage of AudioQueueDispose in Swift

I'm sure this is something stupid I'm doing wrong but why is the swift parser telling me I can't convert the expression's type () when clearly the definition of AudioQueueDispose returns an OSStatus type? I've put off asking this question for a while cos I know it's going to be something dumb I'm just overlooked.
I put this in to Xcode playground for simplicity...
import UIKit
import AudioToolbox
import AVFoundation
var audioQueue:AudioQueue
var status : OSStatus = OSStatus(noErr)
status = AudioQueueDispose(audioQueue, inImmediate: false)
I think the error message was very misleading especially with the little arrow pointing to the '=' sign implying it was an issue with the return type. Anyway, the actual problem is to do with using 'false', which is a swift type 'Bool', whereas the function expects at type 'Boolean' which is in fact a UInt8. So the above can be fixed by writing...
status = AudioQueueDispose(audioQueue, 0)
Perhaps someone can offer a better solution which does not involve using integers?
For now I'm just defining a couple of constants..
let FALSE:Boolean = 0
let TRUE:Boolean = 1