Check if string is a valid double value in Swift - string

In Swift, how can one check if a string is a valid double value? I have been using the following extension from this question (but as a float) but if the value cannot be converted, it simply returns "0":
extension String {
var doubleValue:Double? {
return (self as NSString).doubleValue
}
}
Ideally, I would like it to return nil so it can be caught in an if-let, like so:
if let i = str.doubleValue {
object.price = i
} else {
// Tell user the value is invalid
}

edit/update: Xcode 11 or later • Swift 5.1 or later
You can use Double initializer init?<S>(_ text: S) where S : StringProtocol to create an instance property on StringProtocol and use it to check if a String or Substring is a valid Double:
extension StringProtocol {
var double: Double? { Double(self) }
var float: Float? { Float(self) }
var integer: Int? { Int(self) }
}
Testing
let str = "2.9"
if let value = str.double {
print(value) // "2.9\n"
} else {
print("invalid input")
}
str.prefix(1).integer // 2
str.suffix(1).integer // 9

It is indeed more efficient not to create a number formatter every time we do a conversion:
extension String {
struct NumFormatter {
static let instance = NumberFormatter()
}
var doubleValue: Double? {
return NumFormatter.instance.number(from: self)?.doubleValue
}
var integerValue: Int? {
return NumFormatter.instance.number(from: self)?.intValue
}
}

Why not let it return false? Or true of course.
extension String {
func isInt() -> Bool {
if let intValue = Int(self) {
return true
}
return false
}
func isFloat() -> Bool {
if let floatValue = Float(self) {
return true
}
return false
}
func isDouble() -> Bool {
if let doubleValue = Double(self) {
return true
}
return false
}
func numberOfCharacters() -> Int {
return self.characters.count
}
}
Or even better, as suggested by #LeoDabus:
extension String {
var isInteger: Bool { return Int(self) != nil }
var isFloat: Bool { return Float(self) != nil }
var isDouble: Bool { return Double(self) != nil }
}

Here is my function:
func je_numerik(text:Character)->Bool //en znak
{
if((text=="0")||(text=="1")||(text=="2")||(text=="3")||(text=="4")||(text=="5")||(text=="6")||(text=="7")||(text=="8")||(text=="9")){
return true
}
else
{
return false
}
}
func je_stevilka(text: String)->Bool
{
var pika:Character
pika="."
var je_stevilka=true
//var znaki = Character(text)
var znaki=Array(text)
var stevilo_znakov=znaki.count
if(stevilo_znakov==0)
{
je_stevilka=false
}
else
{
if(stevilo_znakov==1)
{
if(je_numerik(znaki[0]))
{
je_stevilka=true
}
else
{
je_stevilka=false
}
}
else
{
if((je_numerik(znaki[0])) && (!((znaki[0]=="0")&&((znaki[1]=="0"))))&&(!((znaki[0]=="0")&&((je_numerik(znaki[1]))))))
{
var je_pika=false
for var i = 0; i < stevilo_znakov; i++
{
if(je_numerik(znaki[i])||(znaki[i]==pika))
{
if(znaki[i]==pika)
{
if(je_pika)
{
je_stevilka=false
}
else
{
je_pika=true
if(stevilo_znakov==(i+1))
{
je_stevilka=false
}
}
}
}
else
{
je_stevilka=false
}
}
}
else
{
je_stevilka=false
}
}
}
return je_stevilka
}
Just call it like this:
var check_if_is_number=je_stevilka(numberText)

Related

Error: Expected a value of type 'int', but got one of type 'String' Flutter

I'm trying to print my current location and I have this error:
Error: Expected a value of type 'int', but got one of type 'String'
My code:
class AssiMethod {
static Future<String> searchCooredinationAdress(Position position) async {
// ignore: non_constant_identifier_names
String Adressplace = "";
String url =
"https://maps.googleapis.com/maps/api/geocode/json?${position.latitude},${position.altitude}=$mapKey";
var responce = await RequestAssist.getReqeust(url);
if (responce != "echech") {
Adressplace = responce["results"][0]["formatted_address"];
}
return Adressplace;
}
}
class RequestAssist {
static Future<dynamic> getReqeust(String url) async {
http.Response response = await http.get(Uri.parse(url));
try {
if (response == 200) {
String jSondata = response.body;
var decoData = jsonDecode(jSondata);
return decoData;
} else {
return "echec de repense";
}
} catch (exp) {
return "echec";
}
}
}
String adresse = await AssiMethod.searchCooredinationAdress(position);
print("adresse " + adresse);

Unauthorized exception with SPSecurity.RunWithElevatedPrivileges?

I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

Async table query in sequelize getter method

I have a sequelize instance method that performs a DB query:
getPropertyDays() {
const queryString = `
SELECT
state
FROM property_days
WHERE
DATE(day) = CURDATE() AND
property_id = :propertyId;`;
const replacements = {propertyId: this.id};
return this.sequelize.query(queryString, {replacements: replacements, type: sequelize.QueryTypes.SELECT});
},
that gets called by the getter:
getterMethods: {
propertyState() {
var self = this;
const blockedDay = 'x';
const unavailableDay = 'u';
this.getPropertyDays().then(function(result) {
var state = result[0]['state'];
if (self.prospect || state == unavailableDay) {
return 'unavailable';
}
if (state == blockedDay) {
return 'occupied';
}
else {
return 'available';
}
});
}
},
The problem is that the result that is returned from the getter is undefined because he's not able to solve the promise before returning.
Since I don't have a model for the table, how can I solve this issue? Been around this for one day already!
Thanks a lot.
Won't returning the promise returned from this.getPropertyDays do the trick?
getterMethods: {
propertyState() {
var self = this;
const blockedDay = 'x';
const unavailableDay = 'u';
return this.getPropertyDays().then(function(result) {
var state = result[0]['state'];
if (self.prospect || state == unavailableDay) {
return 'unavailable';
}
if (state == blockedDay) {
return 'occupied';
}
else {
return 'available';
}
});
}
},

unit testing with mocha not finding function

So I'm trying to unit test a function I wrote here is the function:
function compareServices(service1, service2) {
if (service1.name != service2.name) {
return false
}
if (service1.port != service2.port) {
return false
}
if (service1.target != service2.target) {
return false
}
if (service1.address != service2.address) {
return false
}
return true
}
it is located inside my main.js file. Now When I try to run the test I get an error saying:
Main #compareServices() should compare if two services match:
TypeError: main.compareServices is not a function
at Context.<anonymous> (test/stelaSpec.js:21:25
And here is my test file:
var expect = require("chai").expect;
var main = require("../src/main.js");
describe("Main", function(){
describe('#compareServices()', function() {
it('should compare if two services match', function() {
var svc1 = {
"name": "test.fg.service",
"port": 8001,
"target": "mac-book",
"address": "192.2.2.2"
}
var svc2 = {
"name": "test.fg.service",
"port": 8001,
"target": "mac-book",
"address": "192.2.2.2"
}
var result = main.compareServices(svc1, svc2);
expect(result).equal(true)
});
});
});
Why is it saying it is not a function when it is?
Make sure to have the following at the end of your main.js file:
module.exports = {
compareServices: compareServices
};
This will make the function accessible to other javascript files that require it.
You change your code for main.js as below:
function compareServices(service1, service2) {
if (service1.name != service2.name) {
return false
}
if (service1.port != service2.port) {
return false
}
if (service1.target != service2.target) {
return false
}
if (service1.address != service2.address) {
return false
}
return true
}
to
// if you use case => In test file you need to declare var main = new Main();
// with Main = require(... + '/main.js');
var Main = function(){};
Main.prototype.compareServices = function(service1, service2) {
if (service1.name != service2.name) {
return false
}
if (service1.port != service2.port) {
return false
}
if (service1.target != service2.target) {
return false
}
if (service1.address != service2.address) {
return false
}
return true
}
module.exports = Main;
Or
var Main = function(){};
Main.compareServices = function(service1, service2) {
if (service1.name != service2.name) {
return false
}
if (service1.port != service2.port) {
return false
}
if (service1.target != service2.target) {
return false
}
if (service1.address != service2.address) {
return false
}
return true
}

What is wrong with this script?

var isEven = function(number) {
if (number%2 === 0) {
return true;
};
else if (isNaN(number) === true) {
return ("please input a number");
};
else {
return false;
};
};
Your script should not have the ; behind your closing brackets
Try this:
var isEven = function(number){
if (number%2 === 0) {
return true;
} else if (isNaN(number)===true) {
return ("please input a number");
} else {
return false;
}
}

Resources