Why can I not remove an unused function from my Swift Class? - xcode

See the function 'postRequest' in this UserModel class I have defined. Well the function is not used anymore anywhere and when I try to remove it XCode syntax highlighting crashes and my program will not compile with a segmentation fault error 11 which points to nowhere.
I moved the function into a struct called SharedModel. So this function is not called anywhere! Why can I not remove it from the file? It makes no sense, I just want to remove an unused function. But Xcode keeps crashing and it makes me keep it! What is going on.
import Foundation
import SwiftHTTP
import SwiftyJSON
public enum UserProperties : String {
case user_id = "user_id", single_access_token = "single_access_token", first_name = "first_name",
last_name = "last_name", role = "role", email = "email", username = "username", barn_id = "barn_id",
location_id = "location_id", farm_id = "farm_id"
static let allValues = [user_id, single_access_token, first_name, last_name, role, email, username, barn_id, location_id, farm_id]
}
class UserModel {
var userPropertiesJSON: JSON?
init () {
}
func postRequest(url: String, params: Dictionary<String,AnyObject>, completionHandler: (JSON?) -> ()) {
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
//The expected response will be JSON and be converted to an object return by NSJSONSerialization instead of a NSData.
request.responseSerializer = JSONResponseSerializer()
//we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
//let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
request.POST(url, parameters: params, success: {(response: HTTPResponse) in
println(response.responseObject!)
let json = JSON(response.responseObject!)
completionHandler(json)
},failure: {(error: NSError, response: HTTPResponse?) in
completionHandler(false)
})
}
func login(username: String, password: String, completionHandler: (Bool) -> ()) {
let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
SharedModel.postRequest("http://farmcentral.softimum.com/user_sessions.json", params: params) { jsonOrError in
if let json: JSON = jsonOrError {
self.userPropertiesJSON = json
SharedModel.userPropertiesJSON = json
completionHandler(true)
} else {
completionHandler(false)
}
}
}
}
UPDATE
Still and issue but I have narrowed it down to the exact line of code that if removed causes xcode to crash and causes the build to stop compiling due to a segment fault 11 error.
This is the offending line: let json = JSON(response.responseObject!)
This line is in the function inside the closure. When I remove this line Xcode crashes. I am running cocoapods beta version, this might be a bug.

This was a bug with the framework I was using called SwiftyJSON. The solution was to import SwiftyJSON.swift file directly into your project.
Here is the Github issue: https://github.com/SwiftyJSON/SwiftyJSON/issues/67

Related

How do you log an objects details to the test console with `cy.log`?

When you do something like the following:
const someObject = {
key: 1,
anotherKey: 'test'
}
cy.log("Some object", someObject)
It will be rendered in the Cypress UI as Some object, Object{2}
Is there a way to get this to print prettier?
I am on version 10.3.0 here is a result with my actual log message:
Actual code:
const loginInput = {
userContext: "global_",
email: finalEmail,
password,
verificationCode,
};
cy.log("Authenticating via GraphQL with the following details", loginInput);
I ran the same code, and it is showing the key-value pairs in the log.
You can use the Javascript Method Object.entries() to loop over the key-value pair and log them one by one.
const someObject = {
key: 1,
anotherKey: 'test',
anotherKey2: 'test2',
}
Object.entries(someObject).forEach(([key, value]) => {
cy.log(key, value)
})

Does not exist on type 'DefaultRootState'. TS2339

I am trying to implement react-redux in login-form input values.
I have added values to the redux state, but I cannot access the data individually from the state object.
Here are the details:
In App.js file
console.log(useSelector((state) => state));
gives result {email: "demo#demo.com" , password: "123456"}
. I am not able to access the email inside the state object using
console.log(useSelector((state) => state.email));
It is giving the error that
'email' does not exist on type 'DefaultRootState'. TS2339
Here is the reducer.js file
let formValues = {
email: "",
password: "",
};
export const inputReducer = (state = formValues, action) => {
switch (action.type) {
case "inputValue":
return { ...state, [action.name]: action.inputValue };
default:
return state;
}
};
Here is the action.txt file
export const handleChange = (name: string, inputValue: string) => {
return {
type: "inputValue",
name: name,
inputValue: inputValue,
};
}
I wrote a function to get rid of this problem :
function getProperty<T, K extends keyof T>(o: T, propertyName: K): T[K] {
return o[propertyName]; // o[propertyName] is of type T[K]
}
You have to pass your object as first parameter, then the name of your property (here it is email or password).
If you want to get all your property at once, you have to encapsulate them in an object property like this:
{ value : {email:"alan.turing#gmail.com",password:"123" } }
i may be late but thought to provide solution. Basically this type of error message appears when you don't provide the typing in the useSelector hook
As per the doc React-Redux which states:
Using configureStore should not need any additional typings. You will,
however, want to extract the RootState type and the Dispatch type so
that they can be referenced as needed.
here in your code block the RootState type is missing, this can be declared in your store file as below
import {createStore} from 'redux';
----------
const store = createStore(rootReducer);
export default store;
export type RootState = ReturnType<typeof store.getState>;
And in your .tsx or .jsx file where exactly you want to access your store values using react-redux hook useSelector add the type as below.
useSelector((state:RootState) => state)

How to change the graphql typedefs name that is coming from json results of external api?

I have encountered an issue with the naming in my typedefs. The error prompting the following.
Syntax Error: Expected Name, found Int "24"
I am using Coinmarketcap Api and accessing it with my apollo graphql server. The api has naming such as 24h_volume_usd, percent_change_1h etc, but as long as integer within the name, it will have this name issue.
I am not really sure how can I fix this issue. Can anyone please help me out? Thank you very much.
Schema.js:
const typeDefs = `
type cryptos {
id: String
name: String
symbol: String
rank: String
price_usd: String
price_btc: String
24h_volume_usd: String
market_cap_usd: String
percent_change_1h: String
available_supply: String
total_supply: String
last_updated: String
}
type Query {
cryptos: [cryptos]
}
`
resolvers.js:
const resolvers = {
Query: {
cryptos: () => {
return axios.get('https://api.coinmarketcap.com/v1/ticker/').
then(result => result.data );
}
}
Process api result using map functions
`var newHashmap = {};
Object.keys(hashmap).forEach(function(key){
var value = hashmap[key];
key = key + "xxx";
console.log("changing:");
console.log(key); newHashmap[key] = value
});`

Issue with RANGE_ADD in Relay Mutations

I was going through the relay docs and came to following code in RANGE_ADD.
class IntroduceShipMutation extends Relay.Mutation {
// This mutation declares a dependency on the faction
// into which this ship is to be introduced.
static fragments = {
faction: () => Relay.QL`fragment on Faction { id }`,
};
// Introducing a ship will add it to a faction's fleet, so we
// specify the faction's ships connection as part of the fat query.
getFatQuery() {
return Relay.QL`
fragment on IntroduceShipPayload {
faction { ships },
newShipEdge,
}
`;
}
getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'faction',
parentID: this.props.faction.id,
connectionName: 'ships',
edgeName: 'newShipEdge',
rangeBehaviors: {
// When the ships connection is not under the influence
// of any call, append the ship to the end of the connection
'': 'append',
// Prepend the ship, wherever the connection is sorted by age
'orderby(newest)': 'prepend',
},
}];
}
/* ... */
}
Now over here it is mentioned that edgeName is required for adding new node to the connection. Looks well and fine.
Now, I move further down the documentation and reached the GraphQL implementation of this mutation.
mutation AddBWingQuery($input: IntroduceShipInput!) {
introduceShip(input: $input) {
ship {
id
name
}
faction {
name
}
clientMutationId
}
}
Now according to docs this mutation gives me output as
{
"introduceShip": {
"ship": {
"id": "U2hpcDo5",
"name": "B-Wing"
},
"faction": {
"name": "Alliance to Restore the Republic"
},
"clientMutationId": "abcde"
}
}
I cannot see edgeName being present here.
I was using graphene for my project. Over there also I saw something similar only
class IntroduceShip(relay.ClientIDMutation):
class Input:
ship_name = graphene.String(required=True)
faction_id = graphene.String(required=True)
ship = graphene.Field(Ship)
faction = graphene.Field(Faction)
#classmethod
def mutate_and_get_payload(cls, input, context, info):
ship_name = input.get('ship_name')
faction_id = input.get('faction_id')
ship = create_ship(ship_name, faction_id)
faction = get_faction(faction_id)
return IntroduceShip(ship=ship, faction=faction)
Over here also I cannot see edgeName anywhere.
Any help please? I am working on mutations for the first so wanted to confirm a m I missing something or is something wrong here?
This example might be either simplified or a bit obsoloete, because in practice there is need to return edge and that's exactly what is fetched by relay (other fields in RANGE_ADD are more a kind of declaration and are not necessarily fetched).
Here is how you can do it in graphene:
# Import valid as of graphene==0.10.2 and graphql-relay=0.4.4
from graphql_relay.connection.arrayconnection import offset_to_cursor
class IntroduceShip(relay.ClientIDMutation):
class Input:
ship_name = graphene.String(required=True)
faction_id = graphene.String(required=True)
ship = graphene.Field(Ship)
faction = graphene.Field(Faction)
new_ship_edge = graphene.Field(Ship.get_edge_type().for_node(Ship))
#classmethod
def mutate_and_get_payload(cls, input, context, info):
ship_name = input.get('ship_name')
faction_id = input.get('faction_id')
ship = create_ship(ship_name, faction_id)
faction = get_faction(faction_id)
ship_edge_type = Ship.get_edge_type().for_node(Ship)
new_ship_edge = edge_type(
# Assuming get_ships_number supplied
cursor=offset_to_cursor(get_ships_number())
node=ship
)
return cls(ship=ship, faction=faction, new_ship_edge=new_ship_edge)

New Parse forces "optional", how to query a PFUser?

I have this code that due to the x-code changes is no longer working.
var query = PFUser.query()
var user = PFUser.currentUser()!.username
query!.whereKey("username", equalTo: "\(user)")
query!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
The problem is that the PFUser.currentUser()!.username aka, the "user" variable now prints out the following : Optional("username")
Therefore, it searches for a username with the text: Optional("") and a username between the quotes.
So it doesn't find a username.
Ever since the last x-code update, the query is requiring this optional crap.
got it to work.
var query = PFUser.query()
query!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query!.findObjectsInBackgroundWithBlock {
added a ! after username in PFUser.currentUser()!.username!

Resources