I have the following code in swift 2
let deviceid = UIDevice.currentDevice().identifierForVendor!.UUIDString
This fails to compile. I tried following suggestions from the auto-fix in xCode and I came up with this.
let deviceid = UIDevice.currentDevice.identifierForVendor!.UUIDString
However it still does not compile. It says value of type 'UUID' has no member UUIDString'
My advice - for these kind of issues - get straight into a playground
let deviceid = UIDevice.current.identifierForVendor?.uuidString
Related
I am trying to format a float into a string with a set number of digits. All the examples I have seen use something like this:
let thisString = String(format: "%2.4f" , 3.14159262)
However, when I try this I get:
Argument labels '(format:, _:)' do not match any available overloads
. Like it doesn't even recognize "format" as a valid way to initialize a string. I am using Swift 5 on Xcode 10.2 on Mojave, if that makes a difference. Am I missing some framework or something? Did the initializer change?
Your code should be working correctly. Can you please try the following:
import Foundation
let firstString = String(format: "%2.4f", arguments: [3.14159262])
print(firstString)
let secondString = String(format: "%2.4f", 3.14159262)
print(secondString)
I have this code running fine in a playground using Swift 5.
Removing the Foundation import gives the same error you described in your question.
I am trying to find a count of entities which satisfy predicate. According to documentation and "header" files, this should work:
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "FileRecord")
let ctx: NSManagedObjectContext = GetCtx()
let res = try ctx.count(for: fetch)
however I get compile error:
Cannot invoke 'count' with an argument list of type '(for: NSFetchRequest<NSFetchRequestResult>)'
however when I create the fetch request from FileRecord like this instead:
let fetch: NSFetchRequest<FileRecord> = FileRecord.fetchRequest()
I get the following error:
Cannot convert value of type 'NSFetchRequest<FileRecord>' to expected argument type 'NSFetchRequest<NSFetchRequestResult>'
Please anyone got an idea what can be wrong? I am a decent C++ language lawyer but I am just a novice with Swift...
EDIT: SOLVED
My example above was wrong. In reality I had code functionally identical to:
let res: UInt64 = try ctx.count(for: fetch)
since count returns Int, the function did not match. The error message was not specific enough for me to see it immediately. Thanks to all who have tried to help :)
I'm trying to do this:
var myBeacons: [NSUUID: [Int]] = [NSUUID(UUIDString:"74278BDA-B644-4520-8F0C-720EAF059935"): [1,1]]
but I get the following error:
'[NSUUID: [Int]]' is not convertible to '[NSUUID: [Int]]'
If I do:
var myBeacons2: [String: [Int]] = ["74278BDA-B644-4520-8F0C-720EAF059935": [1,1]]
It works
Did I miss something or does it look like bug ? (I'm using Xcode 7 beta)
Since not every String is a valid UUID the initialiser can fail. Thus the initialiser returns an Optional<NSUUID>. This to encourage code safety.
Depending on your needs you might check that you supplied a valid String for an UUID as follow:
let givenString = "74278BDA-B644-4520-8F0C-720EAF059935"
var myBeacons: [NSUUID: [Int]] = [:]
if let uuid = NSUUID(UUIDString: givenString) {
// Here we are sure that the uuid is valid
myBeacons[uuid] = [1, 1]
}
As Martin points out, NSUUID(UUIDString:) returns an optional. You need to unwrap it:
var myBeacons: = [
NSUUID(UUIDString:"74278BDA-B644-4520-8F0C-720EAF059935")!: [1,1]]
(Note the exclamation point after the call to the NSUUID initializer.)
I tested that under Xcode 6.3.2 and it works. I Haven't tested it under Xcode 7 though.
Edit:
In fact it would be better to use optional binding as outlined in #MatteoPiombo's answer. You should accept his answer since it gives you the most robust solution. (I'm voting for his answer. It's the best answer so far)
convenience init?(UUIDString string: String) returns an optional, try unwrap it as follow:
var myBeacons: [NSUUID: [Int]] = [NSUUID(UUIDString:"74278BDA-B644-4520-8F0C-720EAF059935")!: [1,1]]
I have recently upgraded to XCode 6.3 and I am trying to initiate an ODQuery as per the Apple Documentation and getting an error.
'Int' is not convertible to 'ODMatchType'
I am using Apple's own Documentation Open Directory Programming Guide
Here is my Swift code:
var err:NSError?
var session = ODSession.defaultSession()
var node = ODNode(session: session, name: "/Local/Default", error: &err)
var query = ODQuery(node: node, forRecordTypes: kODRecordTypeUsers, attribute: kODAttributeTypeRecordType, matchType: kODMatchContains, queryValues: "darren", returnAttributes: kODAttributeTypeStandardOnly, maximumResults: 10, error: &err)?
The issue seems to be that kODMatchContains or any other matchType that are tried are not compatible with the Swift 1.2 function?
If someone knows what is going on or if you can try the code in 6.3 yourself and get the same results, please let me know.
This has nothing to do with Swift 1.2. It was always this way in Swift. The matchType: parameter needs to be an ODMatchType. Coerce it to an ODMatchType, like this:
... matchType: ODMatchType(kODMatchContains), ...
And that line will then compile just fine (once you remove the question mark at the end).
Apparently I have to spell it out for you...
var err:NSError?
var session = ODSession.defaultSession()
var node = ODNode(session: session, name: "/Local/Default", error: &err)
var query = ODQuery(node: node, forRecordTypes: kODRecordTypeUsers, attribute: kODAttributeTypeRecordType, matchType: ODMatchType(kODMatchContains), queryValues: "darren", returnAttributes: kODAttributeTypeStandardOnly, maximumResults: 10, error: &err)
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