swift

findStringLenght()

Parameters: input: String

String whose length we want to find out

Returns: Integer representing length of the string

This program demonstrates how to find the length of a string in Swift. It introduces the '.count' property used on strings to retrieve their length.

Variables
String operations
Built-in methods
Medium dificulty

Writing a Swift Function to Determine String Length

Hello there, fellow programmer! Welcome to this informative blog post. In the steps that will unfold, you will be shown how to program a function to find the length of a string in the Swift language. It's not as hard as it seems, and with some practice, you'll master it in no time. Ready? Let's dive in!

Step 1: Declare a Function

First, you need to declare a function which is going to calculate the length of a string. TypeError: The function declaration in Swift begins with the 'func' keyword followed by the name of the function. We'll name our function 'stringLength'.

func stringLength(string: String) {}

The function 'stringLength' takes one parameter 'string' of String type.

Step 2: Calculate the String Length

In Swift, you can use the 'count' property of the string to get the length of the string. This property returns the number of 'Character' instances in a string.

func stringLength(string: String) {
    let length = string.count
}

Step 3: Return the Length of the String

Now, you need to return the value of the 'length' variable from the function. In Swift, you use the 'return' keyword to return a value from a function.

func stringLength(string: String) -> Int {
    let length = string.count
    return length
}

The function now returns an Int that represents the length of the string.

Step 4: Test the Function

Let's test our function by calling it with a string.

let length = stringLength(string: "Hello World!")
print(length)  // Output: 12

In this example, the function 'stringLength' correctly returned the length of the string 'Hello World!'.

Conclusion

In this post, we've created a simple Swift function that calculates the length of a string. This function uses Swift's built-in 'count' property of the 'String' type, which makes the implementation straightforward and easy.

Here's the full code:

func stringLength(string: String) -> Int {
    let length = string.count
    return length
}

let length = stringLength(string: "Hello World!")
print(length)  // Output: 12

Learn function in:

String length calculation

Compute length of a string in characters

Learn more

Mathematical principle

Understanding the length of a string in programming is similar to understanding the length of a numerical vector in mathematics. In both cases, the '___.count' property (or method) returns the number of items or elements. In strings, these elements are characters.

Learn more