Problem overview
The function concatFirstAndLastChar receives a string s with at least two characters and returns a new two-character string: the first character of s followed by its last character.
For "hello" the answer is "ho". For "Hello World!" it is "H!": every character counts, so the last one is the exclamation mark, and the capital H stays a capital. For "ab" the first and last characters are the whole string, so the answer is "ab".
Approach: ask for characters from each end
In many languages you would write s[0] and s[s.length - 1]. Swift does not allow that. A String can't be indexed with an Int, and this code is rejected by the compiler:
let s = "hello"
print(s[0])
The error says that you cannot subscript a String with an Int and should use a String.Index instead. The reason is that a Swift character can be built from several Unicode pieces, so the n-th character is not at a fixed offset. Finding it means walking through the string.
The lesson avoids indexes completely. prefix(n) keeps the first n characters and suffix(n) keeps the last n. With n equal to 1, each gives exactly the character you need, and neither needs the length.
Another way: Character and String.Index
Indexes do exist in Swift; they are just not integers. s.startIndex is the position of the first character, and s.index(before: s.endIndex) is the position of the last one. Subscripting with them gives a Character, and String(...) turns each one into a string:
let s = "hello"
let first = s[s.startIndex]
let last = s[s.index(before: s.endIndex)]
print(String(first) + String(last)) // ho
There are also the properties s.first and s.last, but they return an optional Character, because an empty string has no first or last character. Using ! to unwrap them would crash on an empty string. prefix(1) and suffix(1) return an empty result there instead, which is why the lesson prefers them: shorter and safe.
Step by step
- Take the first character with
s.prefix(1). - Take the last character with
s.suffix(1). - Convert each one to a
String. Both calls return aSubstring, a view into the original string, and the function must return aString. - Join the two strings with
+and return the result.
The solution in Swift
class Solution {
func concatFirstAndLastChar(_ s: String) -> String {
return String(s.prefix(1)) + String(s.suffix(1))
}
}
Details worth knowing:
- Why
String(...)is needed."hello".prefix(1)has the typeSubstring. Writingreturn s.prefix(1) + s.suffix(1)fails to compile with an error that it cannot convert the return expression of typeString.SubSequence(akaSubstring) to return typeString. Wrapping each piece inString(...)makes a real, independent string. - Characters, not bytes.
prefixandsuffixcount Swift characters. A letter written asefollowed by a combining accent is one character, so it is kept whole instead of being split in two. - It never goes out of range. If
nis bigger than the string,prefix(n)andsuffix(n)return the whole string. An index would trap at run time instead.
Edge cases and common mistakes
- Two characters.
"ab"gives"ab", as the example shows. - Punctuation and digits.
"a9"gives"a9", and"Hello World!"gives"H!": the function never skips characters that aren't letters. - Forgetting the conversion. Returning a
Substringwhere aStringis expected is the most common compile error here. - Using
prefix(2)by mistake. That keeps two characters from the front, which is not the same as the first and last.
Testing
"hello"gives"ho"."Hello World!"gives"H!"."ab"gives"ab"."a9"gives"a9".
