radius
radius

Reputation: 540

Swift Dictionary

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)

Upvotes: 0

Views: 271

Answers (3)

Duncan C
Duncan C

Reputation: 131491

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)

Upvotes: 2

Matteo Piombo
Matteo Piombo

Reputation: 6726

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]
}

Upvotes: 5

David Liu
David Liu

Reputation: 17624

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]]

Upvotes: 0

Related Questions