logo
down
shadow

Extension for Double to accept String as initializer in Swift


Extension for Double to accept String as initializer in Swift

By : btyler97
Date : November 22 2020, 10:33 AM
hop of those help? So, you want to natural-language-parse a string, and generate a floating-point number from it?
Well, the extension is the easy part. Just create a failable initializer for it:
code :
let digits = [
    "zero", "one", "two", "three",
    "four", "five", "six", "seven",
    "eight", "nine",
]

extension Double {
    init?(fromEnglishString s: String) {
        if let digit = find(digits, s) {
            self.init(Double(digit))
        }
        else {
            return nil
        }
    }
}

let d = Double(fromEnglishString: "one")
// d is {Some 1.0}
extension Double: StringLiteralConvertible {
    public typealias StringLiteralType = String
    public typealias UnicodeScalarLiteralType = String
    public typealias ExtendedGraphemeClusterLiteralType = String

    public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
        self.init(stringLiteral: value)
    }

    public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
        self.init(stringLiteral: value)
    }

    public init(stringLiteral value: String) {
        if let d = Double(fromEnglishString: value) {
            self = d
        } else {
            self = 0.0
        }
    }
}

let doubleFromLiteral: Double = "three"
// doubleFromLiteral is {Some 3.0}


Share : facebook icon twitter icon
Swift Error: Cannot find an initializer for type 'Double' that accepts an argument list of type '(String)'

Swift Error: Cannot find an initializer for type 'Double' that accepts an argument list of type '(String)'


By : Thirumurugan Ganesan
Date : March 29 2020, 07:55 AM
hop of those help? You're probably using Xcode 6, so Swift 1.2, but the String initializer for Double is only available in Swift 2 (Xcode 7).
You can always use NSString's doubleValue property:
code :
let t = (temperatureTextField.text! as NSString).doubleValue
check string is int or double , with extension in swift 3

check string is int or double , with extension in swift 3


By : ste5an
Date : March 29 2020, 07:55 AM
I hope this helps you . As @MartinR said, check if the string can be converted to an Int or a Double:
code :
extension String  {
    var isnumberordouble: Bool { return Int(self) != nil || Double(self) != nil }
}

print("1".isnumberordouble)      // true
print("1.2.3".isnumberordouble)  // false
print("1.2".isnumberordouble)    // true
extension String  {
    var isnumberordouble: Bool { return Double(self) != nil }
}
import Foundation

extension String  {
    var isnumberordouble: Bool { return Double(self.trimmingCharacters(in: .whitespaces)) != nil }
}

print("  12 ".isnumberordouble)     // true
Swift struct extension add initializer

Swift struct extension add initializer


By : fateh nonaya
Date : March 29 2020, 07:55 AM
I wish this help you The problem is even though String.Index does conform to Comparable protocol, you still need to specify the Range type you want to work with public struct Range where Bound : Comparable {}
Note: As NSString uses UTF-16, check this and also in the link you've referred to, your initial code does not work correctly for characters consisting of more than one UTF-16 code point. The following is the updated working version for Swift 3.
code :
 extension Range where Bound == String.Index {
    init(_ range: NSRange, in string: String) {
        let lower16 = string.utf16.index(string.utf16.startIndex, offsetBy: range.location)
        let upper16 = string.utf16.index(string.utf16.startIndex, offsetBy: NSMaxRange(range))

        if let lower = lower16.samePosition(in: string),
            let upper = upper16.samePosition(in: string) {
            self.init(lower..<upper)
        } else {
            fatalError("init(range:in:) could not be implemented")
        }
    }
}

let string = "❄️Let it snow! ☃️"

let range1 = NSRange(location: 0, length: 1)
let r1 = Range<String.Index>(range1, in: string) // ❄️

let range2 = NSRange(location: 1, length: 2)
let r2 = Range<String.Index>(range2, in: string) // fatal error: init(range:in:) could not be implemented
extension Range where Bound == String.Index {
  public init?(_ range: NSRange, in string: String) {
    let u = string.utf16
    guard range.location != NSNotFound,
      let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
      let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
      let lowerBound = String.Index(start, within: string),
      let upperBound = String.Index(end, within: string)
    else { return nil }

    self = lowerBound..<upperBound
  }
}
Cannot invoke initializer for type 'Double' with an argument list of type '(String?)' - Swift Storyboard

Cannot invoke initializer for type 'Double' with an argument list of type '(String?)' - Swift Storyboard


By : user7565612
Date : March 29 2020, 07:55 AM
around this issue textField.text is an optional String, so you need to unwrap it before passing the value to a function that doesn’t accept an optional, such as the Double(_ String:) initialiser.
I would use a guard statement to do so. The string may not be able to be parsed as a Double, so that initialiser also returns an optional, which needs to be unwrapped.
code :
@IBAction func showAnswer (_ sender : UIButton) {
    guard let text = textField.text else {
        return
    }
    let temperatures = ["hot","warm","cool","cold"]
    let thresholds : [Double] = [80,60,40,0]

    if let temperature = Double(text) {

        for (i,threshold) in thresholds.enumerated() {
             if temperature >= threshold {
                 fahrenheitLabel.text = temperatures[i]
                 break
                }
             }
         }
     }
}
SWIFT 4.1 Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'

SWIFT 4.1 Cannot invoke initializer for type 'Double' with an argument list of type '(String?)'


By : Theo Harmse
Date : March 29 2020, 07:55 AM
wish help you to fix your issue The error in the topic says that you can't create a Double from an optional String which is true.
To solve it force unwrap the values for Latitude and Longitude.
code :
...
databaseHandle = ref?.child("Community").child("Alert Notifications").observe(.childAdded, with: { (snapshot) in

        defer { self.dummyFunctionToFoolFirebaseObservers() }
        guard let data = snapshot.value as? [String:String] else { return }
        guard let firebaseKey = snapshot.key as? String else { return }

        //                let date = data!["Date"]
        //                let time = data!["Time"]
        let dataLatitude = data["Latitude"]!
        let dataLongitude = data["Longitude"]!
        self.alertIconToDisplay = data["Description"]!

        let doubledLatitude = Double(dataLatitude)
        let doubledLongitude = Double(dataLongitude)
        let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

        print("Firebase post retrieved !")

        //                self .keyaLon = dataKey
        //                self.keyaLonArray.append(firebaseKey)

        print("Longitude Actual DataKey is \(String(describing: firebaseKey))")

        print("fir long \((snapshot.value!, snapshot.key))")
        self.userAlertAnnotation = UserAlert(type: self.alertIconToDisplay, coordinate: recombinedCoordinate, firebaseKey: firebaseKey)
        self.mapView.addAnnotation(self.userAlertAnnotation)


    })
Related Posts Related Posts :
  • Swift/iOS: How to access Object properties when type-casted from Protocol?
  • consecutive statement need to have ; error in swift
  • Trying to create a 32 bpc NSBitmapImageRep, getting hit with errors
  • Does locationManager:didUpdateLocations: method called at the same time in extension and its containing app
  • Can't get Data using SwiftyJSON
  • Convert String to UnsafeMutablePointer<char_t> in Swift
  • inout param with empty object since nil won't work
  • How to align a mask onto an image
  • compiler forcing self inside static method of a function while using dispatch_sync
  • private static variable in struct
  • Conditional "in" for arrays in Swift
  • Modifying UIButton Programmatically
  • Pass type to generic function and compare
  • How to customise the look of the PFSignUpViewController
  • How to take screen shot programmatically (Swift, SpriteKit)
  • Setting NavigationController's NavigationBar translucent property to false causes extra padding
  • Create multiple UIViews when the user taps the screen
  • Filter Array of [AnyObject] in Swift
  • How to add ParseUI to a swift project
  • Can Swift enums have multiple raw values?
  • Using a function() variable in a different Class - Swift
  • Masking an image in Swift using CALayer and UIImage
  • KVC without NSObject (NSPredicate)
  • Any? to Dictionary Cast and retrieving value
  • NSCharacterSet.characterIsMember() with Swift's Character type
  • SCNScene: Calculate projected size of an object
  • How to use contains on a swiftyJSON object
  • Index of element in sorted()
  • How do I initialise a new NSDocument instance in Swift?
  • Multiple functions with the same name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org