Error: 'String' is not convertible to 'String!'
I think the compiler is reporting a wrong error.
You can simplify the expression using
let key: String! = "userTrackingMode"
and then use key
instead of the literal.
That will simplify the expression and will help the compiler to print the real error.
Type inferring is complicated and when the compiler doesn't find a valid type combination, it can show you a wrong error.
Getting error: String is not convertible to 'T'
Can't an
Int
or aString
satisfy a generic requirement that
doesn't have any constraints?!
Sure it can. But that's not the reason the compiler is giving you an error.
Think about it, what happens if you constrain a generic function/parameter within the function body itself?! It will no longer be a generic function!
Imagine if you had wrote your operateOn
function as such:
class Numbers {
func operateOn<T>(_ num1: T, _ num2: T, do task: (T, T) -> ()) {
task("k", num2) // add two strings
}
}
Would you say that T
is generic? Or that it's of type String
? If you made it a String
then can num2
be any generic type it wants to be? It can't!
If it's of type String
then it's no longer generic. Since the compiler can't allow that it will throw that error.
Swift 2.x to swift 3, XCode complaining error : 'String!' is not convertible to 'String'
The issue is that myVar as String
returns String?
instead of String
.
You can instead use myVar as! String
, if you are sure that this conversion will always work.
However, if you are afraid that the forced typecast might return nil optional, you can try a guard
statement.
Error: `'(@lvalue String) - Text' is not convertible to '(String) - Text'` in SwiftUI
This error occurs if you have any item in a stack that has the wrong type, i.e. a type that is not convertible to String. The same error can occurs in the code below:
Text("Hello world")
Text(100)
The strange part is that the error occurs on the first row, even though it is the second row that fixes it. I would verify that you are only using strings in all your Text() to see if that helps.
EDIT: Apparently it can happen no matter what error occurs in the body. It seem that the error occurs on the first item in the body if anything is wrong.
NSString!' is not convertible to 'String'; did you mean to use 'as!' to force downcast?
strCategIds + prCate.strCategoryId as! String!
is compiled as
(strCategIds + prCate.strCategoryId) as! String!
Instead, I think you should:
strCategIds + (prCate.strCategoryId as! String)
ErrorType' is not convertible to 'NSError'
For me, this also happens when using AVFoundation and Core Data in the same project.
To get rid of the error:
'ErrorType' is not convertible to 'NSError'; did you mean to use 'as!' to force downcast?
Or the warnings:
Conditional cast from 'ErrorType' to 'NSError' always succeeds
Forced cast from 'ErrorType' to 'NSError' always succeeds; did you mean to use 'as'?
I did this:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MY_APP_NAME.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch let error as NSError {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
} catch {
// dummy
}
return coordinator
}()
Hope this helps :)
ValueError: could not convert string to float: ' '
The problem is that your string is not just '1151226468812.22'
, but it is '"1151226468812.22"'
. It also contains speech marks ("
). This means that before you convert this to a float, you need to remove the leading and trailing speech marks. Luckily, Python has a very handy string method .strip()
to do this for you.
string.strip(s)
will return a string that has the leading and ending 's'
characters removed
For example:
myString = "#hello#".strip("#")
In this code, myString
would be just 'hello'
In this case, you want to strip row[1]
of the leading and trailing "
characters. You can do this very easily:
row[1].strip("\"")
Swift: 'NSArray?' is not convertible to 'NSArray?'
You are confusing the compiler with too many (superfluous) type annotations.
// tested in Playground
if let results = jsonResult["results"] as? NSArray {
// do something with results
}
Make sure you keep the spacing intact as well.
For completeness, here is how I set up jsonResult
. The question if jsonResult itself is an optional or not has nothing to do with your error message.
let jsonResult = NSDictionary(dictionary: ["results" : [1,2,3,4,5]])
EDIT: Swift 2 version with try catch syntax
var originalDictionary = NSDictionary(dictionary: ["results" : [1,2,3,4,5]])
do {
let data = try NSJSONSerialization.dataWithJSONObject(originalDictionary, options: NSJSONWritingOptions())
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? NSDictionary
if let results = jsonResult!["results"] as? NSArray {
for x in (results as! [Int]) {
print("\(x)")
}
}
}
catch let error as NSError {
print(error.description)
}
catch {
print("no clue what went wrong")
}
Related Topics
Swiftui CPU High Usage on Real-Time Foreach View Updating (Macos)
Set an Horizontal Scroll to My Barchart in Swift
Pass Type to Generic Function and Compare
Reachability Change Notification Should Be Called Only Once
Ambiguous Reference to Member 'Buildblock()'
Module Compiled with Swift X.1 Cannot Be Imported in Swift X.0.2
Ckasset in Server Record Contains No Fileurl, Cannot Even Check for Nil
How to Use Crc32 from Zlib in Swift (Xcode 9)
Strange String.Unicodescalars and Characterset Behaviour
Bridging Header for Flurry.H Not Working with Pod
Detecting Swipes on All Four Directions on Watchkit Using The Storyboard
Swift Increment Int! Not Working
Difference Between Object(Forkey:) and Value(Forkey:) in Userdefaults