Opposite of _Conversion in Swift to Assign to a Value of a Different Type

Cannot assign a value of type '[Thing]' to a value of type '[Any]'

It seems Swift can convert Thing to Any but not [Thing] to [Any].

The reason this works

 objects = Thing.allTheThings().map { $0 }

is that the compiler can infer that the type of $0 is Any, but in the second example

let things = Thing.allTheThings().map { $0 }

it infers $0 to be of type Thing. You end up with the variable things being of type [Thing], which means that the assignment

objects = things

will mean a conversion from [Thing] to [Any] which does not work.

@conversion attribute in Swift 2.0

I can't use the @conversion keyword in Swift 2 either (it was an undocumented API anyway, so it may have been removed without warning).

But you don't need anything fancy to make your UInt extension with Swift 2 anyway:

extension UInt {
var radix8Representation: String {
return String(self, radix: 8)
}
}

let x = UInt(16)
print(x.radix8Representation) // "20"

How to convert one struct to another with same variables Swift (iOS)?

In your case, you already have the constructor that can help you to achieve what you want, so instead of trying to cast the object, create a new one:

universityJoinChatViewModel = UniversityJoinChatViewModel(nameOfModel: universityGroupChatItem)

Swift3.0 Cannot convert value of type 'ClosedRange Index ' to type 'Range Index '

You can use ..< instead of ... for range to be of type Range<Index> instead of ClosedRange<Index>, in which case the call to stringByReplacingCharactersInRange(...) wont yield an error (notice the offsetBy increase by 1).

let range = key.startIndex..<key.index(key.startIndex, offsetBy: 1)
// range is now type Range<Index>

Now, I might be wrong, but it seems as if you simply want the selectorString to be the version of key with the first character uppercased. An alternative method to your range solution you can e.g. use a String extension solution as follows:

extension String { 
var firstCharacterUppercased: String {
guard case let c = self.characters,
let c1 = c.first else { return self }
return String(c1).uppercased() + String(c.dropFirst())
}
}

/* example usage */
let key = "fooBar"
let selectorString = key.firstCharacterUppercased

print(selectorString) // FooBar

Element type changes in type array Any

If you want to convert your values to Int you will need to try to cast your element to Int and in case it fail you need to cast from Any to String and initialize a new integer from it:

let arr: [Any] = [9, 3, "7", "3"]
let arrInt = arr.compactMap { $0 as? Int ?? Int($0 as? String ?? "") }
arrInt // [9, 3, 7, 3]

If you really want to declare your object as Any you will need to cast it to array before trying to iterate its elements:

let arr: Any = [9, 3, "7", "3"]
let arrInt = (arr as? [Any])?.compactMap { $0 as? Int ?? Int($0 as? String ?? "") } ?? []
arrInt // [9, 3, 7, 3]


Related Topics



Leave a reply



Submit