Assign a Default Community to a User Profile Programmatically

Salesforce stores default community to a User Profile in NetworkAffinity object. Using apex we cannot insert the default community to a User Profile. We can make a REST API call to add default community to a User Profile.

Sample Code:

//Get Endpoint URL
String endpointURL = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v48.0/sobjects/NetworkAffinity';
HttpRequest req = new HttpRequest();  
req.setEndpoint(endpointURL);  
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
//Add Community Id as NetworkId and Profile/Permission Id
req.setBody('{"NetworkId":"0DB1I000000TP59WAG","ProfileId":"00e1I000001uXJUQA2"}');
Http http = new Http();
HttpResponse response = http.send(req);
System.debug('response-' + response);

Note: Add your salesforce base URL as remote site settings and then execute above code in developer console anonymous window.