-1

Relatively new to Swift programming.

I get an dictionary from which I need to get the user name (first and last name) and display it in table view cell along with other data.

On iPhone 5 and below as the screen width is only 320, the requirement is to just display the first name and first character of the last name.

E.g: "Howard Mark" to "Howard M"

I am sure that there is an elegant way to extract the required string.

struct ScreenSize
{
    static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
    static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
    static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

struct DeviceType
{
    static let IS_IPHONE_5_OR_LESS = (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH <= 568.0)
}

func functionCall (referralData:[String: Any?])
{
    var myMutableString = NSMutableAttributedString()


    if var nameString = referralData[KEY_FULL_NAME]
        {

              if  DeviceType.IS_IPHONE_5_OR_LESS
              {
                var a = nameString as? NSString

                var arr = a?.components(separatedBy: " ")

                let newStr = arr?[0] as? String
                nameString = newStr
                if((arr?.count)! > 1)
                {
                    if let secondString = arr?[1]
                    {
                        let newStr2 = newStr as? NSString

                        let secondChar = newStr2?.character(at: 0)
                        let stringchar:String! = String(secondChar!)
                        nameString = "\(newStr!) \(stringchar)"
                    }
                }

                print("iPhone 5 or less")
            }
            else
            {
                print("Greater than iPhone 5")
            }
    }
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Marimuthu
  • 437
  • 4
  • 14
  • Not related but why do you cast non-optional `nameString` to optional `NSString`? And why do you annotate a non-optional string `stringchar` to a implicit unwrapped optional string? – vadian Nov 07 '17 at 16:00
  • `I get an dictionary from which I need to get the user name (first and last name) ` — are first and last name separated in the source dictionary? – user28434'mstep Nov 08 '17 at 08:20

3 Answers3

0

maybe like this?

let fullName = "Dominik Pich"
var parts = fullName.components(separatedBy: " ")

if parts.count > 0,
  let lastNameInitial = parts.last?.prefix(1) {
  parts[parts.count-1] = String(lastNameInitial)
}

let truncatedName = parts.joined(separator: " ")

//use
print("fullName: \(fullName)")
print("truncatedName: \(truncatedName)")

I'd wrap it in a nice String extension - e.g. a computed property truncateLast

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
0

The most helpful answer I've found when using Swift's built in substring command is here: https://stackoverflow.com/a/39677331/5495979

Although, using the substring command still requires you to first obtain a range or an index, so it still requires a couple commands to implement.

So Using my preferred method from the SO answer referenced above I would just grab the index of the first character and use the substring command and cast it to a string:

let index = secondString.index(secondString.startIndex, offsetBy: 0)
let stringChar = String(secondString.substring(to: index))

I also wanted to let you know that there appears to be a logic error in your code when obtaining the first letter of the last name. You unwrap what should be the last name in your string components array with if let secondString = arr?[1] but then don't assign the unwrapped string stored in secondString to newStr2 before parsing newStr2 for the first character in the string. As it appears now when you parse the first character of the string with let secondChar = newStr2?.character(at: 0) you will actually be parsing the first character from the first name (since when assigning newStr2 with let newStr2 = newStr as? NSString you are actually assigning the fist entry from the array of name strings since newStr is only assinged with let newStr = arr?[0] as? String)

0

I don't think anyone should be thinking in Swift 3 any more. Here's a Swift 4 example:

var name = "Veeblefetzer Rumplestiltskin"
if let r = name.range(of: " ", options: .backwards, range: name.startIndex..<name.endIndex) {
    name = String(name[name.startIndex..<name.index(r.upperBound, offsetBy: 1)])
}
name // "Veeblefetzer R"
matt
  • 515,959
  • 87
  • 875
  • 1,141