Emacs Go Lang Struct Align Text - emacs

In go we have structs like this:
type person struct {
firstname string
lastname string
age int
address string
}
I want it to be aligned like this
type person struct {
firstname string
lastname string
age int
address string
}
and stuff like
const (
constant1 int = 1
c2 int = 2
const3 int = 3
)
to
const (
constant1 int = 1
c2 int = 2
const3 int = 3
)
I know align-regexp should help here, but i am unable to figure it out.

Have you tried go-mode? It will use fmt or goimport to format you code.

Yes, I am using go-mode and go-fmt both not doing the alignment

go-mode should run gofmt or goimports if you put it in the save hook.
(use-package go-mode
:config
(when (executable-find "goimports")
(setq gofmt-command "goimports"))
(defun jpk/go-mode-hook ()
(add-hook 'before-save-hook #'gofmt-before-save nil 'local))
(add-hook 'go-mode-hook #'jpk/go-mode-hook)
)

Related

Unable to calculate with Optional Variables

I have a simple App with 2 text fields
User just needs to enter Year of Service and Salary
I just need to multiply them.
Would like to output to a text label
(1) I have checked for a nil, and code passes
(2) but I am unable to convert the value to Int for multiplication
(3) debugged section by merely multiplying the Int(UserInputVariable.txt) * any number
(4) and just print. No output to debugging screen
if let var1 = Int(staffYrOfServiceTextField.text!) {
let mult = var1 * 3
print(mult)
}
I expected output to debugging screen
You never "verify" that var1 is not nil in the output debugger.
if let var1 = Int(staffYrOfServiceTextField.text!) {
let mult = var1 * 3
print(mult)
} else {
// If reach here, then Int(staffYrOfServiceTextField.text!) is nil.
print(staffYrOfServiceTextField.text)
print("staffYrOfServiceTextField text does not conform to int or is nil")
}
As per your problem statement, there could be two ways to solve this:
1) When you have the textField's keyboard type only numeric, where you are sure about the input will definitely be integer only.
if let salary = txtFld_Salary.text, let exp = txtFld_YearOfExperience.text {
let multi = Int(salary)! * Int(exp)!
print(multi)
}
2) If you havn't defined the keyboard type and user may enter string values in those then use below code to get the multiplication:
if let salary = txtFld_Salary.text, let exp = txtFld_YearOfExperience.text {
if let intSalary = Int(salary), let intExp = Int(exp) {
let multi = intSalary * intExp
print(multi)
}
}

Return Function not Working When trying to convert Integer into String

import UIKit
var str = "Hello, playground"
let NumberofStopLights: Int = 4
var population: Int
population = 5000
let TownName = "HappyPlace"
let TownDescription = return "/(TownName) has a population of /(population) and /(numberofStopLights) Stop Lights
print (TownDescription)
I want to have the integers automatically go into the /(TownName), /(population) and /(numberStopLights) spaces, tried using the return function but it did not work. SO..... I tried doing this based off another post on Stack Overflow, which said to put return right in front of it but that did not work, so... what next? (Code above)
You don't need the return, also your interpolation is wrong. Should be \() instead of /() and you forgot the last " when declaring your Townname string.
var str = "Hello, playground"
let NumberofStopLights: Int = 4
var population: Int
population = 5000
let TownName = "HappyPlace"
let TownDescription = "\(TownName) has a population of \(population) and \(NumberofStopLights) Stop Lights"
print (TownDescription)
You should also try to use upper and lowercase the correct way, although the compiler doesn't care, but it will make your life a lot easier in the end!

Display of special characters \u{n}

Impossible to find the solution ; it does not work...
I've been on this for hours... A little help will give me the opportunity to sleep without a nightmare...
Where is the error ?
let num: Int = 128150 // smiley = "\u{1F496}" => 128150
var str: String = String(num, radix: 16)
str = str.uppercased()
var wkHex: String = "\\u{"+str+"}" // wkHex = "\u{"+str+"}" not match
wkHex.characters.removeFirst(0) // remove "\" unnecessary at startIndex
let cnt = wkHex.characters.count
let zzz: Array = Array(wkHex.characters)
var car: String = ""
for i in 0...cnt - 1 {
car.append(zzz[i])
}
outputChar.stringValue = car // outputChar is a Label (NSTextField)
// output : \u{1F496} ! instead of : 💖
So the idea is to go from a code point to a character?
let iii = 128150
let char = Character(UnicodeScalar(iii)!)
print(char) // 💖
Swift only allows you to use the \u{...} syntax at compile time. This means that the string won't be turned into the emoji at runtime, when the value of num is known.
To do this, you can use UnicodeScalar:
let unicode = UnicodeScalar(128150)
unicode?.description // 💖

Can't compare string entered through terminal to another string in Swift

I am using the following code to implement basic dictionary using swift. However the compiler is not returning any values. I don't know what seems to be the problem. Need Help!
P.S I'm new to Swift.
import Foundation
var dic = ["Nil":"Neel Goswami","Kirana":"Kinara Shah","Sapre":"Rohan Sapre","JP":"Joy Patel","Shreya":"Shrey Bhat","Ali Bhai":"Aalisha Sheth","Gandhi":"Shlok Gandhi","Binti":"Biyanta Shah","Udgam":"Aayushi Shah"]
dic["Wary"] = "Aishwary Rawat"
dic["Sixer"] = "Ruchir Patel"
dic["Bhikhari"] = "Aabhas Singhal"
var str: String? = "Initial"
println("Enter the pet name: ")
str = NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)
var st: String = str!
for (pet, act) in dic
{
if (pet == st) {
println("His/Her actual name is \(act)")
}
}
The problem is that the string from the user input contains a trailing newline character
(\n). You can fix that by changing
var st: String = str!
to
var st = str!.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
Alternatively, use
var st = str!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
which removes leading and trailing space characters as well.
Note that you could simplify your for-loop to a dictionary lookup:
if let act = dic[st] {
println("His/Her actual name is \(act)")
}

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*