PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to make Decimal conform LosslessStringConvertible in Swift 5?

 August 11, 2022     decimal, extension-methods, swift     No comments   

Issue

I want to convert Decimal to String in Swift 5.

Since I directly tried

String(aDecimalNumber)

Then Xcode gives error message saying:

Decimal needs to conform LosslessStringConvertible

so I add an extension looks like:

extension Decimal: LosslessStringConvertible {
    public init?(_ description: String) {


    }
}

But it won't work. My understanding is to extract the description, which is of String type, to a Decimal. But not sure how to do this?


Solution

Here is a possible implementation:

extension Decimal: LosslessStringConvertible {
    public init?(_ description: String) {
        guard let decimal = Decimal(string: description) else {
            return nil
        }
        self = decimal
    }
}


let d: Decimal? = Decimal("1e9")  //1000000000


Answered By - ielyamani
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing