How to make hyperlinks in SwiftUI

Solution 1:

Swift 5.5 (iOS 15+)

1

Foundation supports Markdown.

Text("[Privacy Policy](https://example.com)")

Explaination

To create a link, enclose the link text in brackets (e.g., [Duck Duck Go]) and then follow it immediately with the URL in parentheses (e.g., (https://duckduckgo.com)).

My favorite search engine is [Duck Duck Go](https://duckduckgo.com).

https://www.markdownguide.org/basic-syntax/#links


2

Use Link

A control for navigating to a URL.

https://developer.apple.com/documentation/swiftui/link

Link("Privacy Policy", destination: URL(string: "https://example.com")!)

Solution 2:

Just as @mahan mention, this works perfectly for iOS 15.0 and above by using markdown language:

Text("[Privacy Policy](https://example.com)")

But if you're using a String variable, and put it into the Text it wouldn't work. Example:

let privacyPolicyText = "Read our [Privacy Policy](https://example.com) here."
Text(privacyPolicyText) // Will not work

Solution for using a String variable

The reason is that Text got multiple initiations. So how do we solve this? The easiest way is just to do:

let privacyPolicyText = "Read our [Privacy Policy](https://example.com) here."
Text(.init(privacyPolicyText))

Result: Read our Privacy Policy here.